简体   繁体   中英

Express can't receive body from axios put request

I am currently using a sample express app that looks like:

const express = require('express')
const app = express()
const port = 3000

app.post('/post', (req, res) => {
    console.log(req)
    res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

And sending an axios post request to the the mapped url in ngrok:

const axios = require('axios')

axios.post(`http://21f935bd559b.ngrok.io/post`, {
    "assetData": "foo"
}).catch(err => {
    console.log(err);
})

And the post request will go through and send me a very large output but there is no body or assetData: "foo" anywhere. What am I doing wrong?

  1. You might have forgotten to use JSON Parser. and
  2. You didn't access the request body, but the request object itself.

If you're dealing with JSON data in the body at the server, then you have to parse it.

then req is a request object which will contain everything about the request, you have to access its body like req.body

const express = require('express')
const app = express()
const port = 3000

// Add this line
app.use(express.json());

app.post('/post', (req, res) => {
    console.log(req.body)
    res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

add that app.use(express.json()); It will parse the incoming request body.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM