2017-02-16 155 views
0

我有一個靜態服務我的Polymer項目的快速服務器。我有一個我需要做的REST API查詢,但是如果我從客戶端創建,它將被CORS阻塞。所以我用express-http-proxy試圖解決這個問題;我將請求發送給它,並重定向到具有REST API端點的服務器。這是一個與node server.js運行我的服務器代碼全部:express-http-proxy仍被CORS策略阻止

var express = require('express'); 
var proxy = require('express-http-proxy'); 

var server = express(); 
server.use('/', express.static(__dirname + '/')); 
server.listen(8080); 
server.use('/rest/api/2/search', proxy('restserver:8877')); 
console.log("Server listening on localhost:8080"); 

當我訪問restserver:在它返回一堆JSON作爲「默認」搜索瀏覽器8877/REST/API/2 /搜索。

在客戶端,我有鐵的AJAX提出這個要求:

<iron-ajax 
      id="getBugs" 
      url="/rest/api/2/search" 
      params='' 
      on-response="handleResponse" 
      debounce-duration="300"> 
     </iron-ajax> 

而在腳本部分,我在ready功能使用this.$.getBugs.generateRequest()發送請求。所以我加載它,期望該請求不被CORS阻止,因爲它正在被服務器代理。相反,鉻devtools給了我這樣的:

XMLHttpRequest cannot load http://restserver:8877/secure/MyJiraHome.jspa. Redirect from 'http://restserver:8877/secure/MyJiraHome.jspa' to 'http://restserver:8877/secure/Dashboard.jspa' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. 

我不明白爲什麼它給我的網址,因爲我從來沒有引用他們,以及爲什麼它的阻止由於CORS,因爲它是從服務器去,而不是客戶端,這是代理的全部要點。

回答

0

服務器可能正在返回一個302重定向,這在使用中間件中未正確處理。

更多的重定向是如何工作的:https://en.wikipedia.org/wiki/HTTP_location

您可以修改Location響應頭克服CORS問題,或者你可以嘗試:

var proxy = require('http-proxy-middleware'); 

var restServerProxy = proxy({target: 'http://restserver:8877', autoRewrite: true}); 

server.use('/rest/api/2/search', restServerProxy); 

上面的例子應自動處理重定向。

0

另一種解決方案是使用HTTP代理中間件正如@chimurai所述。

如果你想代理一個HTTPS服務器,以避免CORS:

const proxy = require('http-proxy-middleware'); 

app.use('/proxy', proxy({ 
    pathRewrite: { 
     '^/proxy/': '/' 
    }, 
    target: 'https://server.com', 
    secure: false 
})); 

這裏安全:假需要設置,以避免UNABLE_TO_VERIFY_LEAF_SIGNATURE錯誤。