How do I set multiple http header fields with the same key in Node.js?

霸气de小男生 提交于 2021-02-04 18:00:05

问题


I'm trying to set up server push with cloudflare, but they require multiple link header fields to push multiple files. However, I can't find any documented way to include multiple header fields with the same key in node.js. I tried providing an array, but that just concatenates them together as the value for a single header field.


回答1:


express

You pass an array of values to res.header('HeaderName', arrayOfValues). Here's a working example and cURL output showing the duplicate response headers. This is not directly documented, but it does work (express@4.14.0).

const express = require('express')
const app = express()
app.get('/', (req, res, next) => {
  res.header('Link', ['Link1', 'Link2'])
  res.send()
})
app.listen(3000)

curl -v localhost:3000 output:

< HTTP/1.1 200 OK
< X-Powered-By: Express
< Link: Link1
< Link: Link2
< Date: Fri, 09 Sep 2016 01:44:22 GMT
< Connection: keep-alive
< Content-Length: 0

node core http

Use res.setHeader(name, arrayOfValues)

const http = require('http')

const server = http.createServer(function (req, res) {
  res.setHeader('Link', ['Link1b', 'Link2b'])
  res.end()
})
server.listen(3000)

curl output:

< HTTP/1.1 200 OK
< Link: Link1b
< Link: Link2b
< Date: Fri, 09 Sep 2016 01:52:53 GMT
< Connection: keep-alive
< Content-Length: 0


来源:https://stackoverflow.com/questions/39397983/how-do-i-set-multiple-http-header-fields-with-the-same-key-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!