简体   繁体   English

Express 无法从 axios put 请求接收正文

[英]Express can't receive body from axios put request

I am currently using a sample express app that looks like:我目前正在使用一个示例 express 应用程序,它看起来像:

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:并向 ngrok 中映射的 url 发送 axios post 请求:

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.并且 post 请求将通过并向我发送一个非常大的输出,但没有 body 或 assetData: "foo" 任何地方。 What am I doing wrong?我究竟做错了什么?

  1. You might have forgotten to use JSON Parser.您可能忘记使用 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.如果您在服务器的正文中处理 JSON 数据,则必须对其进行解析。

then req is a request object which will contain everything about the request, you have to access its body like req.body那么 req 是一个请求对象,它将包含有关请求的所有内容,您必须像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());添加那个app.use(express.json()); It will parse the incoming request body.它将解析传入的请求正文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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