javascript - 如何使用 Expect: 100-continue 标头处理客户端 POST 正文请求流?
问题描述
我是一个不耐烦的学习者
我正在寻找有关如何以这种方式控制客户端和服务器之间的数据流的信息:
我想要的是,客户端发送一个 POST 请求,以及一个 Expect: 100-continue 标头,然后服务器处理标头并验证会话信息,如果一切正常,服务器发送响应状态代码 100,最后客户端发送请求的正文。
我的疑问不是关于标头的验证,而是关于如何规范客户端请求 POST 正文到服务器的数据流,如果验证结果不是预期的拒绝请求并响应客户端请求错误状态
如果有什么方法可以做到这一点,如何正确地做到这一点?我不会说英语,为任何错误道歉,感谢您的帮助。
解决方案
这是节点 12 的示例:
// server.js
const http = require('http')
// This is executed only when the client send a request without the `Expect` header or when we run `server.emit('request', req, res)`
const server = http.createServer((req, res) => {
console.log('Handler')
var received = 0
req.on('data', (chunk) => { received += chunk.length })
req.on('end', () => {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.write('Received ' + received)
res.end()
})
})
// this is emitted whenever the client send the `Expect` header
server.on('checkContinue', (req, res) => {
console.log('checkContinue')
// do validation
if (Math.random() <= 0.4) { // lucky
res.writeHead(400, { 'Content-Type': 'text/plain' })
res.end('oooops')
} else {
res.writeContinue()
server.emit('request', req, res)
}
})
server.listen(3000, '127.0.0.1', () => {
const address = server.address().address
const port = server.address().port
console.log(`Started http://${address}:${port}`)
})
客户端
// client.js
var http = require('http')
var options = {
host: 'localhost',
port: 3000,
path: '/',
method: 'POST',
headers: { Expect: '100-continue' }
}
const req = http.request(options, (response) => {
var str = ''
response.on('data', function (chunk) {
str += chunk
})
response.on('end', function () {
console.log('End: ' + str)
})
})
// event received when the server executes `res.writeContinue()`
req.on('continue', function () {
console.log('continue')
req.write('hello'.repeat(10000))
req.end()
})
推荐阅读
- angular - NgSwitch - 行为出乎意料,`No provider for NgSwitch` - 出现异常
- solace - 只有当它有一个活跃的订阅者时才会创建安慰主题吗?
- jquery - 将鼠标悬停在滑块的左侧或右侧时,如何将光标转向左侧或右侧图标?
- javascript - 如何为表单生成动态唯一 ID,该表单是弹出表单以评论每篇文章但它获取最后一篇文章 ID
- angular - Ionic 4 应用程序不能作为 Electron 应用程序运行
- javascript - 如何从前端订购一系列 api 调用?
- angular - 为 Angular 链下拉菜单设置默认值
- sql - 如何根据匹配数组中包含的值执行 INNER JOIN,该数组本身就是表的字段?
- tsql - 尝试使用 MAX 列解决方案将多行 ROLL-UP 成单行但不起作用
- odata - 如何使用 DataServiceContext 调用接受实体引用参数的未绑定操作?