node.js中res.setHeader和res.header之间的区别

时间:2016-11-28 09:24:52

标签: node.js express

res.setHeader和res.header之间有什么区别。哪一个应该用于启用CORS?在某些页面中使用了res.header,并且一些页面res.setHeader用于CORS。

4 个答案:

答案 0 :(得分:38)

res.setHeader()是Node.js的本机方法,res.header()是Express框架中res.set()方法的别名。

  

文档:res.setHeader()res.set()

这两种方法完全相同,设置标头HTTP响应。唯一的区别是res.setHeader()只允许设置单一标题res.header()将允许您设置多个标题。 所以请使用符合您需求的那个。

答案 1 :(得分:11)

也许一个例子可以澄清更多:

// single field is set 
res.setHeader('content-type', 'application/json');

// multiple files can be set
res.set({
     'content-type': 'application/json',
     'content-length': '100',
     'warning': "with content type charset encoding will be added by default"
  });

答案 2 :(得分:4)

除具有高投票权的答案外,$ rbenv install 2.3.8 1 ↵ Downloading ruby-2.3.8.tar.bz2... -> https://cache.ruby-lang.org/pub/ruby/2.3/ruby-2.3.8.tar.bz2 Installing ruby-2.3.8... WARNING: ruby-2.3.8 is past its end of life and is now unsupported. It no longer receives bug fixes or critical security updates. BUILD FAILED (LinuxMint 19 using ruby-build 20200401-11-g12af1c3) Inspect or clean up the working tree at /tmp/ruby-build.20200519084931.6743.ptWQ7b Results logged to /tmp/ruby-build.20200519084931.6743.log Last 10 log lines: ../../internal.h:84:30: warning: this use of "defined" may not be portable [-Wexpansion-to-defined] linking shared-object json/ext/generator.so make[2]: Leaving directory '/tmp/ruby-build.20200519084931.6743.ptWQ7b/ruby-2.3.8/ext/json/generator' linking shared-object objspace.so make[2]: Leaving directory '/tmp/ruby-build.20200519084931.6743.ptWQ7b/ruby-2.3.8/ext/objspace' linking shared-object nkf.so make[2]: Leaving directory '/tmp/ruby-build.20200519084931.6743.ptWQ7b/ruby-2.3.8/ext/nkf' make[1]: Leaving directory '/tmp/ruby-build.20200519084931.6743.ptWQ7b/ruby-2.3.8' uncommon.mk:203: recipe for target 'build-ext' failed make: *** [build-ext] Error 2 是别名set,它调用header设置标题。这是源代码:

setHeader

另请参见GitHub here

答案 3 :(得分:0)

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, DELETE, OPTIONS"
  );
  next();
});

我将此代码用于我的平均堆栈项目。