我一直试图弄清楚如何用我的Node express服务器从我的react应用程序接收POST请求,并且两者成功连接(如下图所示,当POST从前端发送时)。然而,正如也可以看到的那样,帖子的正文根本没有被阅读,我真的不明白为什么。谁能帮我解释一下发生了什么事?我真的很感激!
下面是我的MyForm.js文件:
import React from 'react'
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { name: '' };
}
handleChange = (event) => {
this.setState({[event.target.name]: event.target.value});
}
handleSubmit = (event) => {
alert('A form was submitted: ' + JSON.stringify(this.state));
fetch('http://localhost:6969/Communication', {
method: 'POST',
body: "five nights at freddys"
}).then(res => {
console.log(res);
});
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} name="name" onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default MyForm;
下面是我的react App.js文件:
import React from "react";
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import MyForm from './MyForm'
function App() {
return (
<div className = "App">
<MyForm />
</div>
);
}
export default App;
下面是我的Node onlineStoreServer.js:
const express = require('express');
const onlineStoreServer = express();
onlineStoreServer.use(express.json());
onlineStoreServer.post("/Communication", async(req, res) => {
console.log("Post received!");
console.log(req.body);
})
onlineStoreServer.listen(6969, () => {
console.log("Listening on port 6969 B)");
});
我试过在post请求中切换数据,也试过在node函数中乱转,但似乎什么都不起作用。我希望body是输入到React应用程序中的名称。
1条答案
按热度按时间z6psavjg1#
看这里你的前端
}
您后端