Axios promise in VUE failed with Cannot read property 'toUpperCase' of undefined - vue.js

In my SPA made in VUE I'm setting my Axios repository (or Api file) but I'm getting trouble using interceptors.
Basically, if the jwtoken is expired or missing the interceptor works and I see in the debug the 401 error and I see in network debug the attempt to the api server.
The issue is when I got a valid jwtoken. In this case I have no attempt in network window and the error:
TypeError: Cannot read property 'toUpperCase' of undefined
at dispatchXhrRequest (app.js:57825)
at new Promise (<anonymous>)
at xhrAdapter (app.js:57808)
at dispatchRequest (app.js:58416)
This should mean a promise error and maybe a config error, but I need fresh eyes to fix...
This is the request code having promise:
const headers = {
'X-CSRF-TOKEN': csrfToken,
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
};
client.interceptors.request.use(
config => {
if (!token) {
return config;
}
const newConfig = {
baseURL,
withCredentials: false,
headers: headers
};
return newConfig;
},
e => Promise.reject(e)
);

The stack trace suggests the problem is in dispatchXhrRequest. There's a call to toUpperCase here:
https://github.com/axios/axios/blob/2ee3b482456cd2a09ccbd3a4b0c20f3d0c5a5644/lib/adapters/xhr.js#L28
So it looks like you're missing config.method.
My guess would be that you need to copy the old config into your new config so you get all the other options, such as method:
const newConfig = {
...config,
baseURL,
withCredentials: false,
headers: headers
};

Related

Trying to GET data from application with Vue and Axios

I'm trying to GET some data from our business server using a GET request with Vue and Axios. I encounter a 401 unauthorized error however. I'm able to GET this data with RESTED when I log in with my company account. I've already looked at this post: How to send Basic Auth with axios but no solution worked for me. This is my code to make the get request:
await axios.get('http://192.168.*******', {}, {
auth: {
username: 'username',
password: 'password'
},
headers: {
'Content-Type': 'application/json'
}
});
}
I've also tried without the 'headers'. This is the error message:
xhr.js:214 GET http://192.******** 401 (Unauthorized)
dispatchXhrRequest # xhr.js:214
[Vue warn]: Unhandled error during execution of created hook
at <App>
createError.js:19 Uncaught (in promise) Error: Request failed with status code 401
at createError (createError.js:19:15)
at settle (settle.js:19:12)
at XMLHttpRequest.onloadend (xhr.js:75:7)
Hopefully someone has an idea because I'm at a loss.
This solution has worked for me:
const config = {
'Content-Type': 'application/json',
"Accept": "application/json",
}
const { data } = await axios({ url: 'http://192.168.170.*****/', method: 'GET', data: null, withCredentials: true, headers: config })

How to solve Cannot read property 'defaults' of undefined in vue?

I am setting default headers in my vue application, but when I load the app it show me error.
main.js?56d7:14 Uncaught TypeError: Cannot read property 'defaults' of undefined
Code
const token = sessionStorage.getItem("token");
if (token) {
Vue.prototype.$http.defaults.header.common["Authorization"] = token;
}
I made a working codepen based on your issue.
In your case, you need to create axios client.
Please check this codepen. https://codepen.io/endmaster0809/pen/VwaPGzr
let apiClient = axios.create({
baseURL: "https://jsonplaceholder.typicode.com",
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})
const token = "testtoken";
if (token) {
apiClient.defaults.headers.common["Authorization"] = token;
}
Vue.prototype.$http = apiClient;

how to use axios to send data to line notify

I tried to send data to line notify server by axios and it fail
I have tried 2 version of code. as shown below
version 1 :
axios({
method: "post",
url: "https://notify-api.line.me/api/notify",
data: 'message="from vue"',
config: {
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "multipart/form-data"
}
},
Authorization: "Bearer [my token]"
})
.then(function(response) {
console.log(response);
})
.catch(function(response) {
console.log(response);
});
response is
XMLHttpRequest cannot load https://notify-api.line.me/api/notify due to access control checks.
Error: Network Error
and version 2 is :
axios
.post("https://notify-api.line.me/api/notify", "message=from vue", {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: "Bearer [my token]"
}
})
.then(response => {
console.log(response);
});
response is
Preflight response is not successful
XMLHttpRequest cannot load https://notify-api.line.me/api/notify due to access control checks.
Error: Network Error
What wrong with is
but I have tried in postman it work fine
Oh I am too familiar with this. Heres an explanation on stackoverflow as to why your request works with postman but not in browser. Long story short browsers send a preflight options check that will ask the server if the action you're about to perform is allowed. Postman does not. Usually the "Access-Control-Allow-Origin": "*" header is sent by the server to the browser not the other way around.
Inside the docs for LINE Notify you can find:
POST https://notify-api.line.me/api/notify
Sends notifications to users or groups that are related to an access token.
If this API receives a status code 401 when called, the access token will be deactivated on LINE Notify (disabled by the user in most cases). Connected services will also delete the connection information.
Requests use POST method with application/x-www-form-urlencoded (Identical to the default HTML form transfer type).
My guess is that your access_token might have been deactivated. Try requiring a new access token and doing the request again.
I think it is impossible to connect directly to the external url for the axios cuz ajax is basically for the inner data network. But you might have a controller if you do a web project, so you can just use your controller language to make a connection with line notify. In my case, I made a rails project and used axios in the vue.js, so I made a link like this.
View(axios) => Controller(Ruby) => LineAPI
me currently work on this too.
I did my app with node js.
My way below is for your reference, it works well.
const axios = require('axios');
const querystring = require('querystring');
axios({
method: 'post',
url: 'https://notify-api.line.me/api/notify',
headers: {
'Authorization': 'Bearer ' + 'YOUR_ACCESS_TOKEN',
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*'
},
data: querystring.stringify({
message: 'something you would like to push',
})
})
.then( function(res) {
console.log(res.data);
})
.catch( function(err) {
console.error(err);
});
I try it works.
async function test() {
const result = await axios({
method: "post",
url: "https://notify-api.line.me/api/notify",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer [token]",
},
data: 'message=你好哇'
})
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
}
test();
I think you can check response on chrome debugger network.
or provide more information, thx.

Axios: Network Error and not sending request

I am trying to send a get request with auth headers to api from Vue using axios.
When I try to send it, it gives me a Network Error with no info about it. I have also check network tab and the request is not sending at all.
Before I checked the url using postman and https://www.hurl.it/ and it worked as expected.
Also, I have sent a request to this api using axios to get a token.
Thank you.
const token = "token";
let options = {
method: 'GET',
url: 'http://smev.test-it-studio.ru/api/analytics/PortfolioStructure',
headers: {
'Authorization': `Bearer ${token}`
},
};
axios(options).then((data) => {
console.log(data);
}).catch((error) => {
console.log(error.config);
});
EDIT: Here is the error I get:
Error
columnNumber: 15
config: {…}
adapter: function xhrAdapter()
baseURL: "http://smev.test-it-studio.ru"
data: undefined
headers: Object { Accept: "application/json", Authorization: "Bearer token"}
maxContentLength: -1
method: "GET"
timeout: 0
transformRequest: Object [ transformRequest() ]
transformResponse: Object [ transformResponse() ]
url: "http://smev.test-it-studio.ru/api/analytics/PortfolioStructure"
validateStatus: function validateStatus()
xsrfCookieName: "XSRF-TOKEN"
xsrfHeaderName: "X-XSRF-TOKEN"
__proto__: Object { … }
fileName: "http://uralsib-lk.dev/dist/build.js"
lineNumber: 19074
message: "Network Error"
response: undefined
stack: "createError#http://uralsib-lk.dev/dist/build.js:19074:15\nhandleError#http://uralsib-lk.dev/dist/build.js:18962:14\n"
__proto__: Object { … }
build.js:18589:24
With the help from Soleno, I found out that it was AdBlock what was blocking the request.
I had this problem in rails. It was cors as mentioned above.
The rails server won't show logs so it looks like axios isn't sending the request at all.
Thankfully it's an easy fix.
For rails add this to your gemfile:
gem 'rack-cors'
Then add this to config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0,Rack::Cors do
allow do
origins 'localhost:8080'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
Note: Update orgins to the origin of your front end app.

api.addAsyncRequestTransform is not a function error

const api = apisauce.create({
// base URL is read from the "constructor"
baseURL,
// here are some default headers
headers: {
'Cache-Control': 'no-cache'
},
// 10 second timeout...
timeout: 10000
})
api.addAsyncRequestTransform(request => async () => {
request.headers['Authorization'] = 'Bearer ' + await AsyncStorage.getItem('#nytevibetoken');
});
throwing api.addAsyncRequestTransform is not a function error. Why? I want to fethc token from AsyncStorage and add it o header. Any suggestion?
The ability to add transformations to async requests was introduced in version 0.10.0 of apisauce.
I attempted to execute your snippet in 0.8.0 and received the same error. Once I upgraded to 0.10.0, the error went away.
Check your package.json dependencies and update apisauce if required.