node 请求数据_使用Node获取HTTP请求主体数据

本文介绍了如何在Node.js中,特别是在使用Express时,提取HTTP请求正文中以JSON格式发送的数据。如果不使用Express,则需要监听流事件来处理请求主体,因为当服务器接收完HTTP头后,但未接收完请求正文时,就会调用回调。
摘要由CSDN通过智能技术生成

node 请求数据

Here is how you can extract the data that was sent as JSON in the request body.

这是在请求正文中提取以JSON发送的数据的方式。

If you are using Express, that’s quite simple: use the body-parser Node module.

如果您使用的是Express,那很简单:使用body-parser Node模块。

For example, to get the body of this request:

例如,获取此请求的主体:

const axios = require('axios')

axios.post('https://flaviocopes.com/todos', {
  todo: 'Buy the milk'
})

This is the matching server-side code:

这是匹配的服务器端代码:

const bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({
  extended: true
}))

app.use(bodyParser.json())

app.post('/endpoint', (req, res) => {
  console.log(req.body.todo)
})

If you’re not using Express and you want to do this in vanilla Node, you need to do a bit more work, of course, as Express abstracts a lot of this for you.

如果您不使用Express并想在普通Node中执行此操作,那么您当然需要做更多的工作,因为Express为您抽象了很多此类内容。

The key thing to understand is that when you initialize the HTTP server using http.createServer(), the callback is called when the server got all the HTTP headers, but not the request body.

要理解的关键是,当您使用http.createServer()初始化HTTP服务器时,当服务器获取所有HTTP标头而不是请求正文时,将调用回调。

The request object passed in the connection callback is a stream.

在连接回调中传递的request对象是

So, we must listen for the body content to be processed, and it’s processed in chunks.

因此,我们必须侦听要处理的主体内容,并且该主体内容是按块处理的。

We first get the data by listening to the stream data events, and when the data ends, the stream end event is called, once:

我们首先通过侦听流data事件来获取data ,然后在数据结束时,一次调用流end事件:

const server = http.createServer((req, res) => {
  // we can access HTTP headers
  req.on('data', chunk => {
    console.log(`Data chunk available: ${chunk}`)
  });
  req.on('end', () => {
    //end of data
  })
})

So to access the data, assuming we expect to receive a string, we must put it into an array:

因此,要访问数据,假设我们希望收到一个字符串,我们必须将其放入数组中:

const server = http.createServer((req, res) => {
  let data = []
  req.on('data', chunk => {
    data.push(chunk)
  });
  req.on('end', () => {
    JSON.parse(data).todo // 'Buy the milk'
  })
})

翻译自: https://flaviocopes.com/node-request-data/

node 请求数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值