我已經在用于node.js的快速框架上編寫了REST API,該API可以處理來自Chrome中的js控制臺和URL欄等的請求?,F在,我試圖使其適用于來自另一個應用程序的請求域(CORS)。由javascript前端自動發出的第一個請求是對/ api / search?uri =的請求,并且似乎在“預檢” OPTIONS請求中失敗。在我的快速應用中,我使用以下方法添加了CORS標頭:var allowCrossDomain = function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With'); // intercept OPTIONS method if ('OPTIONS' == req.method) { res.send(200); } else { next(); }};和:app.configure(function () { app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(allowCrossDomain); app.use(express.static(path.join(application_root, "public"))); app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));});從Chrome控制臺中,我得到了以下標題:請求網址:http://furious-night-5419.herokuapp.com/api/search?uri = http%3A%2F%2Flocalhost%3A5000%2Fcollections%2F1%2Fdocuments%2F1請求方法:OPTIONS狀態碼:200 OK請求標題Accept:*/*Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3Accept-Encoding:gzip,deflate,sdchAccept-Language:en-US,en;q=0.8Access-Control-Request-Headers:origin, x-annotator-auth-token, acceptAccess-Control-Request-Method:GETConnection:keep-aliveHost:furious-night-5419.herokuapp.comOrigin:http://localhost:5000Referer:http://localhost:5000/collections/1/documents/1User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5查詢字符串參數uri:http://localhost:5000/collections/1/documents/1響應標題Allow:GETConnection:keep-aliveContent-Length:3Content-Type:text/html; charset=utf-8X-Powered-By:Express這看起來像API應用程序發送的標題不正確嗎?謝謝。
3 回答

泛舟湖上清波郎朗
TA貢獻1818條經驗 獲得超3個贊
為了支持帶有憑據的Cookie,您需要此行 xhr.withCredentials = true;
mdn docs xhr.withCredentials
在Express Server中,在所有其他塊之前添加此塊
`app.all('*', function(req, res, next) {
var origin = req.get('origin');
res.header('Access-Control-Allow-Origin', origin);
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});`

海綿寶寶撒
TA貢獻1809條經驗 獲得超8個贊
對于大多數瀏覽此問題的人來說,情況可能并非如此,但我也遇到了同樣的問題,解決方案與無關CORS。
事實證明,string在環境變量中未定義JSON Web令牌機密,因此無法對令牌進行簽名。這會導致任何POST依賴于檢查或簽名令牌以獲取超時并返回503錯誤的請求,從而告訴瀏覽器出了點問題CORS,事實并非如此。在Heroku中添加環境變量解決了該問題。
我希望這可以幫助別人。
- 3 回答
- 0 關注
- 684 瀏覽
添加回答
舉報
0/150
提交
取消