Trying to GET data from application with Vue and Axios - api

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 })

Related

How to pass formurlencoded values in post method

Here is my code
axios
.post(
'https://app.adhg.ashdg/m/api/business/get-business',
{
'gid': getgid,
},
{
headers: {
'Cookie': cookie,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
)
.then(function (response) {
// handle success
alert(JSON.stringify(response.data));
})
.catch(function (error) {
// handle error
alert(error.message);
});
I am using Axios to fetch data from API but I am not getting response. I have tried some of the suggestions available in Stack Overflow and from web searches, but nothing helped me. I am getting error like "invalid parameters".
I also tried in Postman with the same parameter and I am getting response. What mistake am I making?
Note
Expected output: I have to get the output like status:1,msg:'success'.
What I am getting is like status:0,msg:'Invalid parameters'

Axios promise in VUE failed with Cannot read property 'toUpperCase' of undefined

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
};

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 POST failed access control check: No 'Access-Control-Allow-Origin' .HTTP status code 405

I don't know what I did wrong and need help.
function loadDoy() {
axios({
method: 'post',
headers: {
"Access-Control-Allow-Origin": "*",
'Content-Type': 'application/json',
},
url: apiPostUrl,
data: {
user: "webuser",
password: "m0nk3yb#rz",
layout: "Main Menu"
},
})
.then(function(response) {
this.token = response.data.token;
//if login token works then get records
getRecords();
})
.catch(function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
});
}
You can use 'crossDomain': true at your header of axios post, this is due to cors error. Your browser is making a Preflight Request, which uses the OPTIONS HTTP method. This is to check whether the server will allow the POST request – the 405 status code is sent in the response to the OPTIONS request, not your POST request
In this case, the following is causing the request to be preflighted:
if the Content-Type header has a value other than the following:
application/x-www-form-urlencoded
multipart/form-data
text/plain
The value for the Content-Type header is set to application/json;charset=utf-8 by axios. Using text/plain;charset=utf-8 or text/plain fixes the problem: You may try using like below.
source: App Script sends 405 response when trying to send a POST request
axios({
method: 'post',
headers: {
'crossDomain': true,
//'Content-Type': 'application/json',
'Content-Type': 'text/plain;charset=utf-8',
},
url: apiPostUrl,
data: {
user: "webuser",
password: "m0nk3yb#rz",
layout: "Main Menu"
},
})
.then(function(response) {
this.token = response.data.token;
//if login token works then get records
getRecords();
})
.catch(function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
});

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.