How to solve problem with Axios post request - javascript

There is such a vue method:
methods: {
sendTrackerClientData () {
return axios.post("https://seo-gmbh.eu/couriertracker/json/couriertracker_api.php?action=tracking.data_save&key_id=00227220201402050613" , {
tracking_data: 'some data'
})
.then(response => {
console.log('post method is working!');
})
.catch(function (error) {
console.log(error);
});
},
}
Which is hung on a button click event
After trying to send data, we can see the warnings and error described above in the firebug.
Trying to add headers by type:
return axios.post("https://seo-gmbh.eu/couriertracker/json/couriertracker_api.php?action=tracking.data_save&key_id="+ this.$store.state.tracker.trackingKeyId , {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'X-Powered-By': 'bacon'
},
tracking_data: this.$store.state.tracker.trackingClientData
})
.then(response => {
console.log('post method is working!');
})
.catch(function (error) {
console.log(error);
});
It didn’t lead to anything.
Question:
How can I solve this problem?

OK, let's break this down:
axios.post("... lots of stuff ..."+ this.$store.state.tracker.trackingKeyId , {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'X-Powered-By': 'bacon'
},
tracking_data: this.$store.state.tracker.trackingClientData
})
The first argument you're passing to post is the URL. I'm going to assume that's the correct URL.
The second argument you're passing is this object:
{
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'X-Powered-By': 'bacon'
},
tracking_data: this.$store.state.tracker.trackingClientData
}
This is wrong in multiple ways.
Firstly, you seem to be trying to add response headers as request headers. Neither Access-Control-Allow-Origin nor X-Powered-By should be there. They should be on the server.
But they aren't actually being set anyway because you've put the headers config in the wrong place. The arguments for post should be url, data, config. The headers need to go in the config, not the data.
axios will set the content-type header automatically. In the case of your request it'll set it to application/json. However, that will trigger a CORS preflight OPTIONS request as it isn't one of the 3 safe-listed content-types.
I don't know what content-type the API you're using expects but if you need to avoid the preflight request then you'll need to set it to one of application/x-www-form-urlencoded, multipart/form-data or text/plain. e.g.:
axios.post("... lots of stuff ..."+ this.$store.state.tracker.trackingKeyId , {
tracking_data: this.$store.state.tracker.trackingClientData
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
However, the data is still being encoded as JSON here (so the content-type header and the request body don't actually match). I believe jQuery defaults to encoding the data as a URL encoded query string. The official axios documentation for doing that is here:
https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format
However, all of this very much depends on exactly what format the server is expecting.
As you only have a single parameter it might be possible to do something like this:
axios.post(
"... lots of stuff ..."+ this.$store.state.tracker.trackingKeyId,
'tracking_data=' + encodeURIComponent(this.$store.state.tracker.trackingClientData),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
)
To debug this further you should carefully inspect the headers being sent each way in the Network tab of your browser's developer tools. Make sure they are exactly what you're expecting. There shouldn't be any mysteries here, you can see exactly what headers are being used.
Further, if you aren't clear on how CORS works and what can trigger a preflight OPTIONS request then you should do some background reading on that.
Finally, you need to find out exactly what format your server is expecting for the data. We can speculate all day about what the correct code might be but if we know what we're aiming for then there's no need to guess.
I would add that the jQuery example you posted has tracking_data spelt incorrectly as traking_data. That won't be related to the CORS error but it makes me wonder whether it really 'works'.

The issue means server restricts cross-origin requests. Those headers you've tried to add should be added on the server side. There is no way you can make it work without modifying your server code/settings.

Related

I can not send parameter using GET with jQuery to node js REST API [duplicate]

I have a React application where I am changing POST method to GET with the request body as it is. It works fine with POST request however when I change the method to GET, it gives me error-
message: "org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public
My Front End Code-
export const setData = (getData) => dispatch => {
axios({
method: 'GET',
url: 'http://localhost:8080/api',
headers: {
'Content-Type': 'application/json'
},
data: getData
})
.then (response => {
dispatch({
type: API_DATA,
payload: response.data
})
dispatch({
type: SET_SEARCH_LOADER,
payload: false
})
})
.catch(function(error) {
})
}
Can someone let me know what I am missing here. As per my understanding, http allows to have a request body for GET method.
As per my understanding, http allows to have a request body for GET method.
While this is technically true (although it may be more accurate to say that it just doesn't explicitly disallow it), it's a very odd thing to do, and most systems do not expect GET requests to have bodies.
Consequently, plenty of libraries will not handle this.
The documentation for Axois says:
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
Under the hood, if you run Axios client side in a web browser, it will use XMLHttpRequest. If you look at the specification for that it says:
client . send([body = null])
Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD.
If you want to send parameters with get request in axios, you should send parameters as params.
If you want to set "Content-type":"application/json" and send params with get request, you should also send an empty data object.
For example:
const AUTH_TOKEN = 'Bearer token'
const config = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': AUTH_TOKEN,
},
data: {},
params: {
"post_id": 1
}
}
axios.get("http://localhost/api/v1/posts/", config)
This is not axios, the error origniates from the java backend you're talking to. The public field in your request body is missing.
If you just want to send the data as parameters (which would be odd), pass it using params instead of data (as shown here: https://github.com/axios/axios#example).
I personally don't think your API should support GET with a request body (talk to the devs and ask for documentation).

How can I send data on request.body in an ajax call? [duplicate]

I have a React application where I am changing POST method to GET with the request body as it is. It works fine with POST request however when I change the method to GET, it gives me error-
message: "org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public
My Front End Code-
export const setData = (getData) => dispatch => {
axios({
method: 'GET',
url: 'http://localhost:8080/api',
headers: {
'Content-Type': 'application/json'
},
data: getData
})
.then (response => {
dispatch({
type: API_DATA,
payload: response.data
})
dispatch({
type: SET_SEARCH_LOADER,
payload: false
})
})
.catch(function(error) {
})
}
Can someone let me know what I am missing here. As per my understanding, http allows to have a request body for GET method.
As per my understanding, http allows to have a request body for GET method.
While this is technically true (although it may be more accurate to say that it just doesn't explicitly disallow it), it's a very odd thing to do, and most systems do not expect GET requests to have bodies.
Consequently, plenty of libraries will not handle this.
The documentation for Axois says:
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
Under the hood, if you run Axios client side in a web browser, it will use XMLHttpRequest. If you look at the specification for that it says:
client . send([body = null])
Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD.
If you want to send parameters with get request in axios, you should send parameters as params.
If you want to set "Content-type":"application/json" and send params with get request, you should also send an empty data object.
For example:
const AUTH_TOKEN = 'Bearer token'
const config = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': AUTH_TOKEN,
},
data: {},
params: {
"post_id": 1
}
}
axios.get("http://localhost/api/v1/posts/", config)
This is not axios, the error origniates from the java backend you're talking to. The public field in your request body is missing.
If you just want to send the data as parameters (which would be odd), pass it using params instead of data (as shown here: https://github.com/axios/axios#example).
I personally don't think your API should support GET with a request body (talk to the devs and ask for documentation).

why data is undefined in post method

I m using react js app and I try to post data to my api , but I got undefined insert for one time .
instead of 'url' I have working url.
this is my post method's code:
senddata(){
if(!this.formvalidation())
{
try{
let resulte = fetch('url',{
method:'post',
mode:'no-cors',
headers:{
'Accept':'application/json',
'Content-type': 'application/json'
},
body:JSON.stringify({
ID:this.state.code,
Blod:this.state.blod,
Allergic:this.state.allergicdescription,
Chronic:this.state.chronic_description
})
});
alert("post");
}catch(e){
alert("not post")
}
}
}
thanks.
You said mode:'no-cors' so any attempt to do anything which requires permission from CORS will fail silently.
Setting 'Content-type': 'application/json' requires permission from CORS.
Presumably, your server side code is not parsing the request body as JSON since the Content-Type header doesn't say it is JSON.
Since there is no parsed data, all the properties you want to read from the JSON will be undefined.
Don't use mode:'no-cors' if you want to POST JSON.

Sending Request body for GET method in AXIOS throws error

I have a React application where I am changing POST method to GET with the request body as it is. It works fine with POST request however when I change the method to GET, it gives me error-
message: "org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public
My Front End Code-
export const setData = (getData) => dispatch => {
axios({
method: 'GET',
url: 'http://localhost:8080/api',
headers: {
'Content-Type': 'application/json'
},
data: getData
})
.then (response => {
dispatch({
type: API_DATA,
payload: response.data
})
dispatch({
type: SET_SEARCH_LOADER,
payload: false
})
})
.catch(function(error) {
})
}
Can someone let me know what I am missing here. As per my understanding, http allows to have a request body for GET method.
As per my understanding, http allows to have a request body for GET method.
While this is technically true (although it may be more accurate to say that it just doesn't explicitly disallow it), it's a very odd thing to do, and most systems do not expect GET requests to have bodies.
Consequently, plenty of libraries will not handle this.
The documentation for Axois says:
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
Under the hood, if you run Axios client side in a web browser, it will use XMLHttpRequest. If you look at the specification for that it says:
client . send([body = null])
Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD.
If you want to send parameters with get request in axios, you should send parameters as params.
If you want to set "Content-type":"application/json" and send params with get request, you should also send an empty data object.
For example:
const AUTH_TOKEN = 'Bearer token'
const config = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': AUTH_TOKEN,
},
data: {},
params: {
"post_id": 1
}
}
axios.get("http://localhost/api/v1/posts/", config)
This is not axios, the error origniates from the java backend you're talking to. The public field in your request body is missing.
If you just want to send the data as parameters (which would be odd), pass it using params instead of data (as shown here: https://github.com/axios/axios#example).
I personally don't think your API should support GET with a request body (talk to the devs and ask for documentation).

POST Request Using fetch() Returns 204 No Content

I'm making a POST request to a node.js server and I'm having trouble getting it to work. Here's my request:
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'this-can-be-anything',
};
export const postVote = (id, vote) =>
fetch(`${uri}/posts/${id}`, {
method: 'POST',
headers,
body: JSON.stringify({options: vote}),
}).then(response => response.json())
.then(data => data)
.catch(err => console.log(err));
The function accepts an 'id' and a 'vote', both strings. The id is being used as part of the URI in the request, and the vote is being supplied as options so the API knows what to do with it. Both of the arguments are being passed correctly:
id = '8xf0y6ziyjabvozdd253nd'
vote = 'upVote'
Here's a link to the GitHub repository for the server/API:
Udacity Readable API
and a screenshot of the network when firing the request:
UPDATE: Added the second screenshot which shows status 200. Though it shows this and appears to have been successful, it still doesn't post to the server and the information stays the same.
What you are looking at is the OPTIONS request in the network tab. For cross origin requests, every request if preceeded by an OPTIONS request which tells the calling client (browser, for example) if those HTTP methods are supported by the remote server for use in crosss origin context.
Check the other requests out. If the OPTIONS request was responded to correctly by the server, the browser must automatically follow up with your POST request
EDIT:
Also, the docs specify the param name to be option whereas in your screenshot it is coming up as options.
Further reading: CORS
Try declaring the headers as such:
var headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'this-can-be-anything',
})

Categories

Resources