How to allow CORS with Node.js (without using Express)

Aer*_*ang 13 javascript node.js

I tried answers from other questions and used (updated from https://gist.github.com/balupton/3696140):

var http = require('http');
var cors = require('cors');

http.createServer(app).listen(3000).use();

function app(request, response) {

response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Request-Method', '*');
response.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
response.setHeader('Access-Control-Allow-Headers', '*');

...

}
Run Code Online (Sandbox Code Playgroud)

It returns: http.createServer(...).listen(...).use is not a function

更新后它运行,但我仍然在客户端收到 405 错误。

Bla*_*mba 12

这是在没有插件的情况下添加 CORS 的详细答案:代码取自此处。

const http = require('http');
const port = 8080;

http.createServer((req, res) => {
  const headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
    'Access-Control-Max-Age': 2592000, // 30 days
    /** add other headers as per requirement */
  };

  if (req.method === 'OPTIONS') {
    res.writeHead(204, headers);
    res.end();
    return;
  }

  if (['GET', 'POST'].indexOf(req.method) > -1) {
    res.writeHead(200, headers);
    res.end('Hello World');
    return;
  }

  res.writeHead(405, headers);
  res.end(`${req.method} is not allowed for the request.`);
}).listen(port);
Run Code Online (Sandbox Code Playgroud)


the*_*jhh 11

无需将其传递给 .writeHead(),现在您可以使用:

response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
response.setHeader('Access-Control-Max-Age', 2592000); // 30 days
Run Code Online (Sandbox Code Playgroud)


jon*_*y89 6

您不想使用 Express,但又尝试使用它的中间件机制。

如果

var server = http.createServer(app).listen(3000)
Run Code Online (Sandbox Code Playgroud)

那么服务器没有该.use功能,该cors模块被设计为中间件,这意味着您需要使用 Express/Connect 才能使用它。

您可以继续不使用expressjs并找到与使用不同的方法cors,例如参见此处https://gist.github.com/balupton/3696140

  • 对于那些到处寻找并想知道为什么他们的手动解决方案仍然不起作用的人:链接的要点最终起作用了,因为它在预检响应和实际响应上都返回了 CORS 标头。 (2认同)

Jam*_*yne 5

这是因为您正在请求一个不那么简单的请求,这意味着它需要处理作为HTTP OPTIONS请求发出的预检请求(因此请确保您的服务器能够响应此方法)。预检请求是在发出实际请求之前请求实际请求权限的一种方式。服务器应该检查上面的两个标头,以验证 HTTP 方法和请求的标头是否有效并被接受。