【问题标题】:How to handle client POST body request flow using Expect: 100-continue header?如何使用 Expect: 100-continue 标头处理客户端 POST 正文请求流?
【发布时间】:2020-08-01 16:45:34
【问题描述】:

我是一个不耐烦的学习者

我正在寻找有关如何以这种方式控制客户端和服务器之间的数据流的信息:

我想要的是,客户端发送一个 POST 请求,连同一个 Expect: 100-continue 标头,然后服务器处理标头并验证会话信息,如果一切正常,服务器发送响应状态码 100,最后客户端发送请求正文。

我的疑问不是对标头的验证,而是关于如何规范客户端请求 POST 正文到服务器的数据流,如果验证结果不是预期的拒绝请求并响应客户端请求错误状态

如果有任何方法可以做到这一点,如何正确地做到这一点? 我不会说英语为任何错误道歉 感谢您的帮助。

【问题讨论】:

  • 为什么需要这样做?
  • 为了提高ram内存的使用,认为应该传输一个非常大的文件,但最终由于与请求头相关的验证,或者由于不相关的内部验证,操作会失败,直到验证发生并出现 4xx 状态代码的响应非常大的文件将作为缓冲区存储在内存中,而不是在文件系统中

标签: javascript node.js server http-post http-status-codes


【解决方案1】:

这里是节点 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()
})

【讨论】:

  • 感谢您花时间提供帮助,我同意给出的解决方案,进一步接受验证所有POST请求都包含标头'期望:100-继续'处理事件'的想法checkExpectation'事件'继续'和函数response.writeContinue ()手动
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-03
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多