Axios from browser not working but working from server - axios

I am using node.js and express to buil my server.
I have some routes from where I'm using axios without problem:
(axios instaled with npm i axios)
const axios=require('axios');
const modelset=await axios({
method: 'get',
url:`https://developer.api.autodesk.com/bim360/modelset/v3/containers/${prIdSandbox}/modelsets`,
headers: {
'Authorization': `Bearer ${internalToken.access_token}`,
},
})
.catch(function(err) {
console.log(err)
})
.then(function(res) {
return res.data.modelSets[0].modelSetId;
})
Also I've using axios from a script loaded into my html page:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="js/ForgeTree.js"></script>
And the ForgeTree.js
const resources=await axios({
method: 'get',
url:`/api/forge/getDocuments/${containerId}/${modelSetId}/${version}`,
})
.catch(function(err) {
/* error in getting data */
console.log(err)
})
...
It has been working, but suddenly it fails:
ForgeTree.js:139 Uncaught (in promise) TypeError: axios is not a function
at getViewableModels (ForgeTree.js:139:27)
at HTMLDivElement.<anonymous> (ForgeTree.js:181:3)
at HTMLDivElement.dispatch (jquery.min.js:2:43064)
at v.handle (jquery.min.js:2:41048)
at Object.trigger (jquery.min.js:2:71515)
at S.fn.init.triggerHandler (jquery.min.js:2:72194)
at a.jstree.plugins.sort.trigger (jstree.min.js:2:12286)
at a.jstree.plugins.sort.activate_node (jstree.min.js:3:12893)
at a.jstree.plugins.sort.<anonymous> (jstree.min.js:2:8477)
at HTMLAnchorElement.i (jquery.min.js:2:88757)
It looks like if I have lost axios in the browser...could some one help?

Change
const axios=require('axios');
to
const axios=require('axios').default;
It's major change for Axios 1.0 or you can change library path to https://unpkg.com/axios#0.27.2/dist/axios.min.js to use like it's use to.

It has been fixed without doing anything...stop working for one day...

Related

rest-hapi standalone endpoint not returning handler results

Forgive me if it's a silly question, but the last time I coded in javascript was almost 20 years ago... I'm re-learning javascript these weeks and I'm not sure I got it all.
I'm using hapi with rest-hapi and want to add some standalone endpoints, basically translating the backend portion of this Autodesk tutorial form express.
I'm using the basic rest-hapi example main script, and tried to add a route with the following code:
//api/forge.js
module.exports = function(server, mongoose, logger) {
const Axios = require('axios')
const querystring = require('querystring')
const Boom = require('boom')
const FORGE_CLIENT_ID = process.env.FORGE_CLIENT_ID
const FORGE_CLIENT_SECRET = process.env.FORGE_CLIENT_SECRET
const AUTH_URL = 'https://developer.api.autodesk.com/authentication/v1/authenticate'
const oauthPublicHandler = async(request, h) => {
const Log = logger.bind('User Token')
try {
const response = await Axios({
method: 'POST',
url: AUTH_URL,
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
data: querystring.stringify({
client_id: FORGE_CLIENT_ID,
client_secret: FORGE_CLIENT_SECRET,
grant_type: 'client_credentials',
scope: 'viewables:read'
})
})
Log.note('Forge access token retrieved: ' + response.data.access_token)
return h.response(response.data).code(200)
} catch(err) {
if (!err.isBoom){
Log.error(err)
throw Boom.badImplementation(err)
} else {
throw err
}
}
}
server.route({
method: 'GET',
path: '/api/forge/oauth/public',
options: {
handler: oauthPublicHandler,
tags: [ 'api' ],
plugins: {
'hapi-swagger': {}
}
}
})
}
The code works and I can display the access_token in nodejs console, but swagger doesn't get the response:
At first I thought that an async function cannot be used as handler, but my hapi version is 17.4.0, and it supports async handlers.
What am I doing wrong?
It turns out it was an easy fix: I just needed to specify the Hapi server hostname in my main script!
The problem was with CORS, since Hapi used my machine name instead of localhost. Using
let server = Hapi.Server({
port: 8080,
host: 'localhost'
})
solved my problem.

Vuejs soap client

I'm considering moving a project to Vuejs and I have a lot of .net soap webservices already created and tested. I know that I can use axios to interact with REST webservices, but can i consume the .net soap webservices from vue ? I already serch and I can't find anything that fits... any idea ?
Basically I need to replace this code without use jquery:
$.ajax({type: 'POST', url: webservice_url , data: data_to_send,
contentType: 'application/json; charset=utf-8', dataType: 'json',
success: function (response) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
Yes, you can interact with Soap from Vue via Axios.
Your code will look like this:
axios({
method: 'post',
url: webservice_url,
data: data_to_send
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
https://github.com/axios/axios - axios documentation with extended examples and good example with SOAP is this link:
https://stackoverflow.com/a/49153096/5808830

Service in vue2JS - error in created hook

I'm new to vue2JS and currently I am trying to create my very first service in vue2 ever.
I've created basic file api.js with this code:
import axios from 'axios';
export default () => {
return axios.create({
baseURL: 'http://localhost:8080/',
timeout: 10000,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
}
Code above is basic axios configuration which will be used in every service across entire app.
I import this file into my service:
import api from '../api.js';
export default {
getLatest () {
return api().get(`http://localhost/obiezaca/ob_serwer/api/article/getLatest.php`, {
headers: {
'Content-Type': 'application/json'
}
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
}
}
Code above is responsible for making http request to backend rest API which give JSON in response.
And then finally I want to use this service inside my component <script></script> tags:
<script>
import { getLatest } from '../../../services/articles/getLatest';
export default {
data () {
return {
articles: []
}
},
created () {
const getLatestService = new getLatest();
console.log(getLatestService);
}
}
</script>
Here I want to execute code from service and actually execute this http request then save response in getLatestService constant and then console.log it and I should be able to see JSON in my browser console.
This doesn't work and give me this error in chrome console:
[Vue warn]: Error in created hook: "TypeError: WEBPACK_IMPORTED_MODULE_0__services_articles_getLatest.a is not a constructor"
And this error in command line:
39:35-44 "export 'getLatest' was not found in '../../../services/articles/getLatest'
Please help me to solve this problem. Additionally I want to refactor my code from service (second one) to use async await but I just can't find good example which would show me way to accomplish that.
EDIT 22.11.17
I added error which show in command line and { } when importing in component. I still didn't solve the problem.
EDIT 24.11.17
Looking for an answer I add more explanation of code I've posted and screenshot of files structure if maybe it can help.
I have check your code and what i can see is, in your api.js you have used
baseURL: 'http://localhost:8080/',
and in your service file
return api().get(`http://localhost/obiezaca/ob_serwer/api/article/getLatest.php`
In your service file you have not define your localhost port, i think it should be like
return api().get(http://localhost:8080/obiezaca/ob_serwer/api/article/getLatest.php
If above is not an your issue then you should try
const getLatestService = getLatest();
Because getLatest() is a function and not an object.
This might solve your error issue.

Ajax request with ionic to local server

i'm new to ionic and ajax.
I have a local restful server that returns json outputs and it works normally with the browser.Then, with ionic i'm trying to get the same response in order to handle that output.
The problem is that the server returns nothing, even with the command "ionic serve". The error function runs instead the success one.
Can someone help me?
This is the script used to make the ajax request
var rootURL = "http://127.0.0.1:8080/conv1";
$(document).ready(function() {
$.ajax({
type: 'GET',
url: rootURL+'/relat/view',
dataType: "json",
success: function(data){
$('#divTrip').append('<ul>');
$.each(data, function(i, rows){
$('#divTrip').append('<li >'+rows.nome+ ' '+rows.cognome+'<br></li><br>');
});
$('#divTrip').append('</ul>');
alert(data[0].cognome);
},
error: function(e){
alert('Error: '+e);
}
});
});

ember-simple-auth facebook authenticator

Trying to hook up facebook authentication for my app. I've got the backend working correctly but my authenticator (I think this is the problem) is always returning undefined.
Copying the example from from ember-simple-auth the console log on line 23 is never called, making me think something else the issue?
import Ember from 'ember';
import Torii from 'ember-simple-auth/authenticators/torii';
const {inject: {service}} = Ember;
export default Torii.extend({
torii: service(),
ajax: service(),
authenticate() {
const ajax = this.get('ajax');
return this._super(...arguments).then((data) => {
return ajax.request('http://localhost:8080/api/login', {
type: 'POST',
dataType: 'application/json',
data: {
'grant_type': 'facebook_auth_code',
'auth_code': data.authorizationCode
}
}).then((response) => {
console.log("CALLED!");
return {
access_token: response,
provider: data.provider
};
});
});
}
});
The response from the server is the access_token from facebook;
How can I better debug/solve what's going on here?
The problem was actually a simple error with the dataType used. It should be dataType: 'json' not dataType: 'application/json'