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'
})
})
node 请求数据