Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

javascript - Empty body in fetch post request

i'm struggling with the fetch API in javascript. When i try to POST something to my server with fetch, the request body an empty array. But when i use Postman it works... Here is my server code in NodeJS :

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)

and here is my client:

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 on the SERVER side, the req.body is empty. Can someone help me? Thank you !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...