問題描述
我正在為 Javascript 中的 fetch API 苦苦掙扎.當(dāng)我嘗試使用 fetch
方法將某些內(nèi)容發(fā)布到我的服務(wù)器時(shí),請求正文包含一個(gè)空數(shù)組.但是當(dāng)我使用 Postman 時(shí),它可以工作.這是我在 Node.js 中的服務(wù)器端代碼:
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)
這是我的客戶端代碼:
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)
})
問題是 req.body
在服務(wù)器端是空的.
The problem is that the req.body
is empty on server side.
推薦答案
問題是
mode: 'no-cors'
來自文檔...
防止方法成為除 HEAD、GET 或 POST 之外的任何東西,并且防止標(biāo)頭成為除 簡單標(biāo)題
Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers
簡單內(nèi)容類型標(biāo)題限制允許
文本/純文本
,application/x-www-form-urlencoded
,以及multipart/form-data
這會使您精心設(shè)計(jì)的 Content-Type: application/json
標(biāo)頭變?yōu)?content-type: text/plain
(至少在通過 Chrome 測試時(shí)).
This causes your nicely crafted Content-Type: application/json
header to become content-type: text/plain
(at least when tested through Chrome).
由于您的 Express 服務(wù)器需要 JSON,它不會解析此請求.
Since your Express server is expecting JSON, it won't parse this request.
我建議省略 mode
配置.這將使用默認(rèn)的 "cors"
選項(xiàng).
I recommend omitting the mode
config. This uses the default "cors"
option instead.
由于您的請求不是 簡單,您可能需要添加一些 CORS 中間件您的 Express 服務(wù)器.
Since your request is not simple, you'll probably want to add some CORS middleware to your Express server.
另一個(gè)(有點(diǎn)老套)選項(xiàng)是告訴 Express 將 text/plain
請求解析為 JSON.這允許您將 JSON 字符串作為簡單請求發(fā)送,這也可以避免飛行前 OPTIONS
請求,從而降低整體網(wǎng)絡(luò)流量...
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']
}))
在 app.use
最終代碼塊中添加了結(jié)束括號.
Added ending parenthesis to app.use
final code block.
這篇關(guān)于獲取 POST 請求中的空正文的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!