douye4051
2016-01-07 20:07
浏览 225
已采纳

如何在Express JS中使用多个Http Header(同名)

My Php Code can be send two headers with same name, in php second parameter is for replace or override. but in ExpressJS res.header is not like php code PHP Code:

header("Link: <http://$prefetch_next_img>; rel=prefetch",false); 
header("Link: <http://$prefetch_next_img2>; rel=prefetch",false);  

http://us2.php.net/manual/en/function.header.php

ExpressJS(NodeJS) :

res.header('Link','Fake Value');
res.header('Link','Only Send it'); // previous header replaced

图片转代码服务由CSDN问答提供 功能建议

我的Php代码可以发送两个具有相同名称的标题,在php中第二个参数用于替换或覆盖。 但是在ExpressJS中 res.header 不像php代码 PHP代码:

  header(“Link:&lt; http:// $ prefetch_next_img&gt;  ; rel = prefetch“,false);  
header(“Link:&lt; http:// $ prefetch_next_img2&gt ;; rel = prefetch”,false);  
   
 
 

http: //us2.php.net/manual/en/function.header.php

ExpressJS(NodeJS):

  res.header('Link','Fake Value'); 
res.header('Link','Only Send it');  //上一个标题被替换为
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • douchong4730 2016-01-07 21:04
    最佳回答

    Ultimately, you'll need to pass an array to set multiple values for the same header

    res.header('Set-Cookie', ['foo', 'bar']);
    

    Looking at response library for express we can see the following examples:

    /**
     * Set header `field` to `val`, or pass
     * an object of header fields.
     *
     * Examples:
     *
     *    res.set('Foo', ['bar', 'baz']);
     *    res.set('Accept', 'application/json');
     *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
     *
     * Aliased as `res.header()`.
     *
     * @param {String|Object} field
     * @param {String|Array} val
     * @return {ServerResponse} for chaining
     * @public
     */
    

    A deeper dive into the code shows us that this is really just a proxy for node's response.setHeader(), which follows the same format

    Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here if you need to send multiple headers with the same name.

    response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题