浏览器的CORS设置 – >网站 – > API服务器

我目前正在运行两个站点,一个基于PHP,一个基于node.js。 node.js版本是API,所以我们称之为“api.com”

PHP网站(php.com)是基于HTML / JSangular度的可视网站“php.com”,使用angular度资源POSTs调用“api.com”。

所以一切都很好,直到最近我开始gettting这个错误。

MLHttpRequest cannot load https://api.com/create. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://php.com' is therefore not allowed access. The response had HTTP status code 400. 

所以有几件事要注意。 该api.com是从一个https网站,其中PHP是http。

在node.js restify api.com网站,它正在做我认为是必要的CORS支持。

  // Allow CORS since other sites may be calling this server.use( function crossOrigin(req,res,next){ res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept" ); // was "X-Requested-With" return next(); } ); 

但是它似乎仍然给出相同的CORS错误。 我是新来的这个CORS的东西,所以不知道是否需要发出头来允许这个调用发生的PHP服务器或节点服务器?

为了理智,我尝试向php.com .htaccess文件添加以下内容…

 Header set Access-Control-Allow-Origin "*" 

但仍然没有运气。 真的很困惑,发生了什么事情,以及如何正确地做到这一点。 我很确定这是一个简单的错误,我正在做任何build议,非常感谢解释如何

**浏览器(铬) – >networking服务器(php.com) – > api服务器(node.js)**

以及哪个服务器应该发送CORS报头

Restify有一个内置的CORS插件。从文档 :

 server.use(restify.CORS({ origins: ['https://foo.com', 'http://bar.com', 'http://baz.com:8081'], // defaults to ['*'] credentials: true, // defaults to false headers: ['x-foo'] // sets expose-headers })); 

使用server.opts方法来处理您的OPTIONS请求的处理程序。 以下是您可以使用的示例。

另外告诉我,如果你正在使用set-credentials标志为true,同时从浏览器发出请求。 这种情况下的句柄将不得不通过访问cookie来响应。

在下面的例子中,我返回了准确匹配的允许来源。 你可以调整它也是子串匹配。 但始终返回响应头“Access-Control-Allow-Origin”中请求头原点中的确切值。 这是一个很好的做法。

 server.opts('/api/(.)*', (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 eg 1. res.setHeader('Access-Control-Max-Age', 864000); return res.send(200); });