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.
Related
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).
So I have to make requests to various urls with different domains which contains credentials
I've successfully managed to send one like this:
const resp = await fetch(`my-url-here`, {
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'Authorization': `Basic ${base64.encode(my-key-here)}`
},
body: JSON.stringify(data)
})
However this works only for one domain while on the other I keep getting
[TypeError: Network request failed] on Android
[SyntaxError: JSON Parse error: Unexpected identifier "undefined"] on iOS (while executing the .json() method; I think the request is successful but with an empty response)
Every call on these domains work correctly using PostMan/ThunderClient
Any idea how to solve this?
Please share how you are processing response seems like request works fine but somehow there is an error while parsing the data into JSON.
invalid data contains in response which is not able to parse into JSON.
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).
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.
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).