簡體   English   中英

無法使CORS與Restify一起使用,所有飛行前選項返回405

[英]Can not get CORS to work with restify, all preflight OPTIONS return with 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'));

我也嘗試添加以下選項:

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.

有任何想法嗎? 這是與再調整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請求編寫自己的處理程序。 以下是您可以使用的示例。

還要告訴我在瀏覽器發出請求時是否使用set-credentials標志為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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM