I use fetch() to post json data as below
var data = {
name: this.state.name,
password: this.state.password
}
fetch('http://localhost:3001/register/paitent', {
method: 'POST',
body: JSON.stringify(data),
mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(res => res.json())
I always get {} in request.body in my express server router, and I figure out the problem is in sending request, it's always 'text/plain'. Why this happens?
I use fetch() to post json data as below
var data = {
name: this.state.name,
password: this.state.password
}
fetch('http://localhost:3001/register/paitent', {
method: 'POST',
body: JSON.stringify(data),
mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(res => res.json())
I always get {} in request.body in my express server router, and I figure out the problem is in sending request, it's always 'text/plain'. Why this happens?
Share Improve this question asked Mar 22, 2018 at 12:14 Bing LanBing Lan 1,1511 gold badge13 silver badges26 bronze badges2 Answers
Reset to default 7You set the mode to no-cors
.
Setting the Content-Type to application/json
requires permission from CORS…
The only allowed values for the Content-Type header [without triggering a preflight CORS request] are:
- application/x-www-form-urlencoded
- multipart/form-data
- text/plain
— mdn
…which you told fetch
not to ask for. Since you don't ask for permission, you don't get permission, so fetch reverts to text/plain
.
I was stuck on same issue for hours now figure out exact solution for this as mentioned in documentation of expressjs @Quentin has pointed towards exact issue. Here I am posting some more details so it may help someone else to resolve this issue quickly.
When you are posting JSON object with 'Content-Type':'application/json'
fetch or any other method browser will request for CORS setting first for security reason then if it receives CORS options which is very easy to achieve. Then it will post original object to server as NodeJS server is waiting for 'Content-Type':'application/json'
You can check documentation of CORS setting on expressjs.. You just need to install CORS package and add this line in your file:
app.options("/data",cors());
This will setup preflight CORS response for your browser for specific /data
path. Your method will look like this:
app.post('/data',cors(),function(req,res){}
Now you can post data with 'Content-Type':'application/json'
. I remend you to read CORS article on MDN for better understanding.