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'
})
Related
I have a Vuex Authentication that stores the state of signed-in user data. It works okay during sign in but if I reload the page after signing in the mutation payload returns no data because for some reason the axios request URI changes, it removes the /api after reloading the page not sure why.
You must save a token sent from the server to do this
To do this, when the server sends you a token, you must save it in the localstorage in your browser.
like this code in mutations method:
login(state, payload) {
axios({
headers: {
'Content-Type': 'application/json'
},
method: 'POST',
url: 'http://127.0.0.1:8000/api/user/login',
data: payload
}).then((response) => {
if (response.data.token) {
state.user_token = response.data.token;
localStorage.setItem('user_token', state.user_token)
}
}).catch((error) => {
console.log(error)
});
}
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.
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`
Post Functionality in Vue.js is returning a null value.
The API Call is local to my machine on a different port. The GET Functionality work as expected. The POST functionality doesn't work as expected only returns null.
fetch('http://localhost:8080/Exercise/lists/add', {
method: 'POST',
headers: {
"Content-Type" : "application/json",
},
body: JSON.stringify(this.user)
})
.then((response) => {
if(response.ok) {
console.log('Response is Ok.');
}
})
.catch((err) => {console.log(err)});
}
Expected to add a user. Rather returns a null value.
Console.log output here..
PostMan "post" service
PostMan "post" service working..
According to this site, the body of the post request is formated like 'foo=bar&lorem=ipsum'. But in your case the data are a JSON stringified object like "{"x":5,"y":6}". This could make a difference for your backend.
Also you can control the requests between your browser and the backend with the browser's network insepector (for Firefox it's Ctrl+Maj+J, then Network tab). It will tell you what data you send to your server and what is the response.
You should use Axios for API calls in Vue. You can find the Axios reference from the documentation https://v2.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html.
According to the documentation from Google when you use the POST request method you need to pass body and the image you uploaded shows you used firstName param. So either change your API and use body to get the first name or you can do something like this:
fetch('http://localhost:8080/Exercise/lists/add?firstName='+JSON.stringify(this.user), {
method: 'POST',
headers: {
"Content-Type" : "application/json",
},
body: ''
})
.then((response) => {
if(response.ok) {
console.log('Response is Ok.');
}
})
.catch((err) => {console.log(err)});
}
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.