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. Anyone know what I'm doing wrong? I'm console logging and sending to postman.
Here is 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
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:
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({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:
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
. Now it will not work. You need to set up a proxy to avoid this problem. Here's the way https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development . Or you can just use axios.post('http://localhost:4444/server')
Note: if you use axios.post('http://localhost:4444/server')
, you will face to the cors issue. Use this to eliminate that issue https://www.npmjs.com/package/cors
这通常是通过将urlencoded扩展名设置为true引起的,请尝试以下操作:
app.use(bodyParser.urlencoded({ extended: false }))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.