我已经生成了两个项目,一个使用create-react-app创建,另一个使用express generator创建。
我在本地主机上分别运行这两个项目,第一个运行在localhost:3000端口,第二个运行在localhost:3001端口。
我正在尝试发送POST请求,但是我收到了一个空的req.body响应体。
客户端代码如下:
我在本地主机上分别运行这两个项目,第一个运行在localhost:3000端口,第二个运行在localhost:3001端口。
我正在尝试发送POST请求,但是我收到了一个空的req.body响应体。
客户端代码如下:
handleSubmit(event) {
event.preventDefault();
var data = new FormData();
for (const key of Object.keys(this.state)) {
data.append(key, this.state[key]);
}
const url = "http://localhost:3000/course";
fetch(url, {
method: "POST",
body: this.state
})
.then(response => response.text())
.then(html => console.log(html));
}
服务器端:
app.js
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.use("/course", course);
router/course.js
router.post("/", function(req, res) {
if (!req.body) {
var course = new Course(req.body);
course
.save()
.then(item => {
res.json({ course: item });
})
.catch(err => {
res.status(500).send("Unable to save to database");
});
}
res.status(200).send("No data to save");
});
package.json
中添加了代理吗?"proxy": "http://localhost:3001",
- Modigbody: this.state
应该改为body: data
吧? - Stamoscreate-react-app
并且有这个Node后端,你需要设置"proxy": "http://localhost:XXXX"
(这是你的Node服务器的端口)。 - Modig