[英]ExpressJs request body is empty
我在localhost:5000
有一個快速應用程序,在localhost:3000
有一個react應用程序。
我通過打來電話
fetch(`${backendUrl}/charge`, {
method: "POST",
mode: "no-cors",
headers: {
"Content-Type": "application/json"
},
body: {
stripeToken: token,
chargeAmount: this.state.donationAmount
}
})
並回應
function route(req, res) {
console.log(req.body);
}
服務器應正確配置為可與CORS一起使用,但主體仍為空。
//configure env variables
require("dotenv").config();
//import packages
var express = require("express");
var bodyParser = require("body-parser");
var cors = require("cors");
//import route functions
const StripeRoute = require("./StripeRoute");
//setup app
const app = express();
const port = process.env.PORT || 5000;
//setup bodyparser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//Setup CORS
app.use(cors());
app.options("*", cors()); // include before other routes
//Connect functions to API routes
app.post("/charge", StripeRoute);
module.exports = app;
根據文檔 , body
選項應該是幾種特定類型之一,而Object
不能是其中之一。
嘗試使用JSON字符串:
body: JSON.stringify({
stripeToken: token,
chargeAmount: this.state.donationAmount
})
編輯 :因為您使用的是no-cors
,所以您無法設置Content-Type application/json
。 相反,您需要生成一個URL編碼的字符串,並將Content-Type
設置為application/x-www-form-urlencoded
(因為no-cors
僅在使用“簡單標頭”的情況下才有效,如此處及后續內容所述)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.