I'm working on a project with Vue using the Spotify API and get stuck trying to get the access token. I'm using axios to make the request but every time I get a 400 status from the server.
This is the way I'm doing it, I have the request inside an action in my Vuex store and I'm not sure if I'm missing something.
axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
params: {
grant_type: 'authorization_code',
code: payload.code,
redirect_uri: process.env.VUE_APP_REDIRECT_URI
},
headers: {
'Authorization': 'Basic ' + (new Buffer(process.env.VUE_APP_CLIENT_ID + ':' + process.env.VUE_APP_CLIENT_SECRET).toString('base64')),
'Content-Type': 'application/x-www-form-urlencoded'
},
json: true
})
.then((response) => {
//handle success
resolve(response);
})
.catch((error) => {
//handle error
reject(error);
})
I would try using data instead of params.
I think data is for the POST body and params is for query string parameters.
Axios Cheat Sheet
You should inspect the request to see what you're sending and then compare that to what you should be sending.
Related
I am trying to call an api using axios. The required params, headers I am passing correctly but on api hit I am returning response as api error: {"message":"Unauthorized"}. I tried with too many solutions like using bearer, jwt token, I also changed API calling library to fetch but still no success.
axiosGetWithHeaders('url',
{
param1: 'emailid'
},{
Authorization : 'token',
ContentType: 'application/json',
}
).then((res) => {
console.log("RESPONSE", JSON.stringify(res))
})
.catch((error) => {
console.error('api error: ' + JSON.stringify(error));
console.error('api error: ' + JSON.stringify(error.response.data));
});
Try with axios:
axios.defaults.headers.common["Authorization"] = accessToken;`enter code here`
I'm trying to make a simple POST request using axios library inside of vuejs but for some reason, DRF is not receiving the parameters. When the same request is made via Postman it receives the parameters.
VueJS
postLogin(credentials){
return axios({
method: "POST",
url: "company/login/",
data: credentials,
}).catch(err => {
return TreatErrors.treatDefaultError(err);
})
}
DRF
#action(methods=['post'], detail=False)
# Debug set here shows POST comes empty from vuejs
def login(self, request, pk=None):
if not request.POST.get('email'):
raise ValidationError({
'message': 'You must provide an email'
})
Using the Chrome DevTools I can clearly see the parameters are being sent to DRF
What I have tried
I have tried coping every Headers from Postman and paste it in axios but without any luck
postLogin(credentials){
return axios({
method: "POST",
url: "company/login/",
data: credentials,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).catch(err => {
return TreatErrors.treatDefaultError(err);
})
}
Basically, I was accessing the data in the wrong way:
From this:
if not request.POST.get('email'):
raise ValidationError({
'message': 'You must provide an email'
})
To This
data = request.data
if not data.get('email'):
raise ValidationError({
'message': 'You must provide an email'
})
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.
I am using axios in my Vue project, and one of the calls to my api involves a POST. Both my posts and gets require that the Authorization header be set with my token. All get requests work fine, but putting the exact same headers in axios.post results in a 403.
Here is my axios code:
axios.post('https://my.example.org/myapi/meta?uname=' + uname + '&umetaid=' + post.umeta_id + '&umetavalue=' + post.meta_value, {
withCredentials: true,
headers: { 'Authorization': 'Bearer ' + mytoken }
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
This always results in a 403 error, and checking my request headers show that the Authorization header is never sent. If I change axios.post to axios.get above (and add a GET method to my api code, in addition to the existing POST,OPTIONS), it will execute just fine. I suppose I could leave it this way, but I think it is bad practice to use a GET call when one really is performing a POST. Is there something I am missing about forming a POST request with axios?
Axios Post request assumes that the second parameter is data and third parameter is config.
Axios Get request assumes that the second parameter is config while the data is appended in URL.
You are sending data in the url which should be as second parameter(For POST request).
Code Should be:
var data = {
'uname': uname,
'umetaid': post.umeta_id,
'umetavalue': post.meta_value
}
var headers = {
withCredentials: true,
headers: { 'Authorization': 'Bearer ' + mytoken }
}
axios.post('https://my.example.org/myapi/meta',data,headers)
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
I am making Log In page for my react native application. My api sends different response when my username and password are valid and invalid. So I want to track and save the status of my response in some state variable and then later perform function accordingly. Please suggest me way to do that.
doSignUp() {
console.log("inside post api");
fetch('MyApiUrl', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
password: this.state.password,
email:this.state.email,
name: this.state.firstname,
last_name :this.state.last_name,
mobile:this.state.mobile,
ssn:"2222222"
})
}).then((response) => {console.log('response:',response.status);
response.json()}
.then((responseData) => {
console.log("inside responsejson");
console.log('response object:',responseData)
console.log('refresh token:',responseData[0].token.refresh_token)
console.log('access token:',responseData[0].token.access_token);
}).done();
}
As far as I understand you want to know the http status code of your fetch request.
Usually your response object includes a "status" property. So you should be able to receive the status code by using this:
response.status
In case of a successful request this will return 200.