[英]req.body is empty and I can't figure out why
我是表达和节点的新手,我正在尝试向我的服务器发布一个axios帖子,但是当我在节点中的console.log时,req.body将变空。 谁知道我做错了什么? 我是控制台记录并发送给邮递员。
这是server.js
const app = require('express')()
const bodyParser = require('body-parser');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/', (req, res) => {
res.send('hello')
})
const port = 4444;
app.post('/send', (req, res) => {
console.log('body: ', req.body)
res.status(200).send(req.body)
});
app.listen(port, () => {
console.log('We are live on port 4444');
});
我的axios电话
export default class Form extends Component {
constructor(props) {
super(props)
this.state = {
name: 'kaleb',
message: '',
email: '',
number: '',
sent: false
}
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
handleSubmit = () => {
axios.post("/send", {name: this.state.name}).then(() => {
console.log(this.state.name)
})
}
在server.js中试试这个:
app.use(bodyParser.json());
app.use(bodyParser.json({type: 'application/*+json'}));
app.use(bodyParser.urlencoded({extended: false}));//or true whatever you need
axios电话:
axios({method:'post',url:'/send',data:{name:this.state.name}})
.then(console.log(this.state.name));
尝试将url作为http://localhost:4444/send
到你的axios调用中:
handleSubmit = () => {
axios.post("http://localhost:4444/send", {name: this.state.name}).then(() => {
console.log(this.state.name)
})
好的,这是我在阅读完所有上述评论后的想法。
localhost:3000/server
而不是localhost:4444/server
。 现在它不会起作用。 您需要设置代理以避免此问题。 这是https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development的方式。 或者您可以使用axios.post('http://localhost:4444/server')
注意: 如果您使用axios.post('http://localhost:4444/server')
,您将面临cors问题。 使用它来消除该问题https://www.npmjs.com/package/cors
这通常是通过将urlencoded扩展名设置为true引起的,请尝试以下操作:
app.use(bodyParser.urlencoded({ extended: false }))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.