所以我在從 React 向我的 Express 服務器后端發出發布請求時遇到了問題:據我所知,請求有效負載的結構是正確的,并且我能夠從服務器發回硬編碼的回應并在前端。
但是,問題是資料本身似乎沒有到達服務器 - 當我在服務器上使用 console.log(req.body) 時,它是undefined. 我完全被難住了。
檢查請求時的網路選項卡:
- 標頭狀態為 200,請求已完成
- Payload 顯示格式正確的 json 物件
body: {url: "https://example.com"} - 回應也正確回傳!
{response: "foo"}
客戶端API函式:
const callBackendAPI = async (query) => {
const response = await axios.post('/', {
body: { url: query },
});
}
注意:我已經添加"proxy": "http://localhost:3001"到客戶端的 package.json 中。
在服務器中:
const express = require('express');
const app = express();
app.post('/', (req, res) => {
console.log(req.body); // <------ **Here's the issue, there's nothing here**
res.json({ response: 'foo' });
// however, if I send res.json(req.body), the response is empty in Network tab
});
uj5u.com熱心網友回復:
您可以使用正文決議器庫:
安裝使用:
npm install body-parser
const express = require('express');
const app = express();
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.post('/', (req, res) => {
console.log(req.body); // <------ **Here's the issue, there's nothing here**
res.json({ response: 'foo' });
// however, if I send res.json(req.body), the response is empty in Network tab
});
顯然,他們已經express.json()根據https://github.com/expressjs/express/releases/tag/4.16.0從 4.16.0 開始添加回來。所以你也可以在express.json()不安裝 body-parser 的情況下使用。
const express = require('express');
const app = express();
app.use(express.json())
app.post('/', (req, res) => {
console.log(req.body); // <------ **Here's the issue, there's nothing here**
res.json({ response: 'foo' });
// however, if I send res.json(req.body), the response is empty in Network tab
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/393245.html
