這是我的 index.js 代碼,即使資料是從前端傳遞的,它也會回傳一個空物件
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
app.use(express.json());
app.post("/api/register", (req, res) => {
console.log(req.body);
res.json({ status: "ok" });
});
app.listen(8000, () => {
console.log("listening on port 8000 . . . ");
});
uj5u.com熱心網友回復:
對于您正在談論的特定情況,您通常需要 oa 正文決議器才能訪問表單輸入欄位。我建議您在其之上構建的最小示例如下:
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
其他一些提示
確保使用標頭 Content-Type: application/x-www-form-urlencoded 或 Content-Type: application/json 提交請求 檢查是否有任何 CORS 問題 Here's More reference for you
uj5u.com熱心網友回復:
如果您正在使用multipart/form-data或需要從前端上傳檔案,您將需要一個multer作為您的發布/補丁請求的中間件,否則您可以將前端設定為發送application/json
[編輯] 您的 index.js 中似乎缺少這一行
app.use(express.urlencoded({extended: true}))
uj5u.com熱心網友回復:
這不起作用的主要原因是在正文中傳遞的資料是文本格式的,而req.body在期望 json 資料時,請確保仔細'Content-Type':'application/json'檢查請求中的設定headers
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/417379.html
標籤:
