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