[英]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.