[英]req.body is empty and I can't figure out why
I'm new to express and node and I'm trying to make an axios post to my server but the req.body is coming up empty when I console.log in node. 我是表达和节点的新手,我正在尝试向我的服务器发布一个axios帖子,但是当我在节点中的console.log时,req.body将变空。 Anyone know what I'm doing wrong?
谁知道我做错了什么? I'm console logging and sending to postman.
我是控制台记录并发送给邮递员。
Here is server.js 这是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');
});
My axios call 我的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)
})
}
try this In server.js: 在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 call: axios电话:
axios({method:'post',url:'/send',data:{name:this.state.name}})
.then(console.log(this.state.name));
Try putting the url as http://localhost:4444/send
in your axios call: 尝试将url作为
http://localhost:4444/send
到你的axios调用中:
handleSubmit = () => {
axios.post("http://localhost:4444/send", {name: this.state.name}).then(() => {
console.log(this.state.name)
})
Ok, Here's what I think after read all of the above comments. 好的,这是我在阅读完所有上述评论后的想法。
localhost:3000/server
instead of localhost:4444/server
. localhost:3000/server
而不是localhost:4444/server
。 Now it will not work. axios.post('http://localhost:4444/server')
axios.post('http://localhost:4444/server')
Note: if you use axios.post('http://localhost:4444/server')
, you will face to the cors issue. 注意: 如果您使用
axios.post('http://localhost:4444/server')
,您将面临cors问题。 Use this to eliminate that issue https://www.npmjs.com/package/cors 使用它来消除该问题https://www.npmjs.com/package/cors
这通常是通过将urlencoded扩展名设置为true引起的,请尝试以下操作:
app.use(bodyParser.urlencoded({ extended: false }))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.