We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
示例代码:/lesson07/server.js
POST数据量通常较大,通常不会一次性从客户端发送到服务端,具体每次发送的大小由协议,以及客户端与服务端之间的协商决定。
因此,Nodejs在处理POST数据时,需要通过request对象的data事件,获取每次传输的数据,并在end事件调用时,处理所有获取的数据。
request对象是一个http.IncomingMessage 类,而它实现了可读流接口,因此具有了可读流的data、end等事件。
需要注意的是,data事件中传入的参数是Buffer,Buffer只是一个二进制的数据,它有可能只是一段字符串数据,也有可能是文件的一部分,所以处理Buffer数据的时候要注意这一点。
const http = require('http') const querystring = require('querystring') const server = http.createServer((req, res) => { let bufferArray = [] // 用于存储data事件获取的Buffer数据。 req.on('data', (buffer) => { bufferArray.push(buffer) // 将Buffer数据存储在数组中。 }) req.on('end', () => { // Buffer 类是一个全局变量,使用时无需 require('buffer').Buffer。 // Buffer.concat方法用于合并Buffer数组。 const buffer = Buffer.concat(bufferArray) // 已知Buffer数据只是字符串,则可以直接用toString将其转换成字符串。 const post = querystring.parse(buffer.toString()) console.log(post) }) }) server.listen(8080)
The text was updated successfully, but these errors were encountered:
No branches or pull requests
阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里。
处理POST数据
POST数据量通常较大,通常不会一次性从客户端发送到服务端,具体每次发送的大小由协议,以及客户端与服务端之间的协商决定。
因此,Nodejs在处理POST数据时,需要通过request对象的data事件,获取每次传输的数据,并在end事件调用时,处理所有获取的数据。
request对象是一个http.IncomingMessage 类,而它实现了可读流接口,因此具有了可读流的data、end等事件。
需要注意的是,data事件中传入的参数是Buffer,Buffer只是一个二进制的数据,它有可能只是一段字符串数据,也有可能是文件的一部分,所以处理Buffer数据的时候要注意这一点。
The text was updated successfully, but these errors were encountered: