无法让CORS与restify一起工作,所有飞行前选项都以405返回



在这一点上,我已经阅读了很多文章,并尝试了我能想到的几乎所有配置,以使CORS与restify一起工作。我已经使用了restify.CORS()restify.fullResponse()以及其他组合。我也试过只使用cors-lib(npm-install-cors),但没有成功。我的应用程序看起来像:

/**
 * Setup middlewares.
 */
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.cors());
server.use(restify.fullResponse());
server.use(morgan('dev'));

我还尝试添加opts处理:

server.opts('/.*/', (req, res, next) => {
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS, DELETE');
  res.send(204);
  return next();
});

在任何情况下,我都会返回:

XMLHttpRequest cannot load http://localhost:3000/1.0.0/clients. Response to preflight 
request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is 
present on the requested resource. Origin 'http://run.plnkr.co' is therefore not 
allowed access. The response had HTTP status code 405.

有什么想法吗?这与restify 4.0.3有关。谢谢

使用CORS:的内置模块

server.use(restify.CORS({
  origins: ['*'],
  credentials: false, // defaults to false
  headers: ['']  // sets expose-headers
}));

如果您确实添加了Access Control Allow Origin标头,那么您的解决方案应该也能正常工作;-)

使用server.opts方法为OPTIONS请求编写自己的处理程序。下面是您可以使用的示例。

还要告诉我,如果您在从浏览器发出请求时使用设置凭据标志为true。在这种情况下,此句柄必须使用访问cookie进行响应。

在下面的示例中,我将返回允许的原点以进行精确匹配。您也可以将其调整为子字符串匹配。但始终返回在响应标头"Access Control Allow origin"中的请求标头原点中找到的确切值。这是一个很好的做法。

server.opts('/.*/', (req, res) => {
const origin = req.header('origin');
const allowedOrigins = ['example.com', 'example.org'];
if (allowedOrigins.indexOf(origin) === -1) {
    //origin is not allowed
    return res.send(405);
}
//set access control headers to allow the preflight/options request
res.setHeader('Access-Control-Allow-Origin', header);
res.setHeader('Access-Control-Allow-Headers', 'Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
// Access-Control-Max-Age header catches the preflight request in the browser for the desired
// time. 864000 is ten days in number of seconds. Also during development you may want to keep
// this number too low e.g. 1.
res.setHeader('Access-Control-Max-Age', 864000);
return res.send(200);

最新更新