ExpressJs路由响应res.send
正在发送,但是响应主体为空。在客户端记录的Promise的then
回调中,响应显示一个键为body: null
的对象。
如果我尝试在then
之后使用res.json()
回调,它将永远不会触发。 res.text
触发回调,但不传递任何内容。
有人知道为什么res.send发送一个空对象吗?
服务器
//configure env variables
require("dotenv").config();
//import packages
var express = require("express");
var bodyParser = require("body-parser");
var cors = require("cors");
//setup app
const app = express();
const port = process.env.PORT || 5000;
//setup bodyparser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//Setup CORS
app.use(cors());
app.options("*", cors()); // include before other routes
//Connect functions to API routes
app.post("/charge", app.post("/charge", (req, res) =>{res.send({asd:"ASDASD"}); });
);
//export app for local testing or lambda serverless running
module.exports = app;
客户端
fetch(`${backendUrl}/charge`, {
method: "POST",
mode: "no-cors",
headers: {
'Accept': 'application/json',
"Content-Type": "application/x-www-form-urlencoded"
},
body: encodeURIComponent(
JSON.stringify({
stripeToken: token.id,
chargeAmount: Math.round(100 * this.state.donationAmount) // Needs to be an integer in cents
})
)
})
.then(res => {
console.log(res);
return res.text();
})
.then(json => {
console.log("response is " + json);
this.setState({ donationResponse: "Thank you for donating!" });
})
.catch(error => {
this.setState({
donationResponse:
"There was an issue processing your request. Please try again later"
});
});