Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 557
TimE Avatar asked Sep 08 '16 18:09

TimE


People also ask

Can you have multiple HTTP headers with the same name?

Multiple HTTP headers of the same name have been detected. RFC 7230 states a server must not generate multiple header fields with the same field name unless either the entire field value for that header field is defined as a comma-separated list, or the header field is a well-known exception.

Can HTTP header have multiple values?

The HTTP Headers can have one or more values depending on the header field definitions. A multi-valued header will have comma separated values. Here are a few examples of headers that contain multiple values: Cache-Control: no-cache, no-store, must-revalidate.

Can you have multiple accept headers?

A client application or browser can request for any supported MIME type in HTTP Accept header. Technically, Accept header can have multiple values in form of comma-separated values.

How do I pass a header in node JS?

We will use request. setHeader() to set header of our request. The header tells the server details about the request such as what type of data the client, user, or request wants in the response. Type can be html , text , JSON , cookies or others.


1 Answers

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 ([email protected]).

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
like image 53
Peter Lyons Avatar answered Sep 18 '22 12:09

Peter Lyons