2017-03-23 25 views
1

我目前正在運行的兩個網站,一個基於PHP,基於Node.js的一個。 node.js版本是API,所以我們稱之爲「api.com」CORS設置爲瀏覽器 - >網站 - > API服務器

PHP網站(php.com)是HTML/JS基於角度的視覺網站「php.com」,通過調用「api .com「使用角度資源POSTs。

所以一切都很好,直到最近,我開始流汗此錯誤。

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 "*" 

但同樣仍然沒有運氣。 真的很困惑,發生了什麼事以及如何正確地做到這一點。我敢肯定,這是一個簡單的錯誤我在做,所以任何的建議是在解釋如何

**瀏覽器(Chrome)不勝感激 - > Web服務器(php.com) - > API服務器(node.js的)**

和服務器(S)應派出的CORS頭

+0

的可能的複製[如何禁用OPTIONS請求?(http://stackoverflow.com/questions/29954037/how-to-disable-options-request) – Quentin

回答

2

的RESTify有一個CORS插件內置 從docs

​​
1

使用server.opts方法爲OPTIONS請求提供自己的處理程序。以下是您可以使用的示例。

還告訴我,如果你正在使用的設置證書標誌設置爲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 e.g. 1. 
    res.setHeader('Access-Control-Max-Age', 864000); 
    return res.send(200); 
    });