Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
130
rated 0 times [  132] [ 2]  / answers: 1 / hits: 32738  / 6 Years ago, thu, january 3, 2019, 12:00:00

I'm struggling with the fetch API in Javascript.
When I try to POST something to my server with fetch method, the request body contains an empty array. But when I use Postman it works.
Here is my server-side code in Node.js:


const express = require('express')
const app = express()
const port = 3000

app.use(express.json())
app.post('/api', function (req, res) {
console.log(req.body)
})
app.listen(port)

Here is my client-side code:


fetch('http://"theserverip":3000/api', {
method: 'POST',
headers: { "Content-Type": "application/json" },
mode: 'no-cors',
body: JSON.stringify({
name: 'dean',
login: 'dean',
})
})
.then((res) => {
console.log(res)
})

The problem is that the req.body is empty on server side.


More From » node.js

 Answers
34

The issue is



mode: 'no-cors'


From the documentation...




Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers




The simple content-type header restriction allows




  • text/plain,

  • application/x-www-form-urlencoded, and

  • multipart/form-data



This causes your nicely crafted Content-Type: application/json header to become content-type: text/plain (at least when tested through Chrome).



Since your Express server is expecting JSON, it won't parse this request.



I recommend omitting the mode config. This uses the default cors option instead.






Since your request is not simple, you'll probably want to add some CORS middleware to your Express server.



Another (slightly hacky) option is to tell Express to parse text/plain requests as JSON. This allows you to send JSON strings as simple requests which can also avoid a pre-flight OPTIONS request, thus lowering the overall network traffic...



app.use(express.json({
type: ['application/json', 'text/plain']
}))


EDIT: Added ending parenthesis to app.use final code block.


[#52842] Wednesday, December 26, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dallasb

Total Points: 657
Total Questions: 98
Total Answers: 97

Location: Luxembourg
Member since Tue, Jan 25, 2022
2 Years ago
;