2015-02-11 112 views
0

我有快遞server.js這樣的配置:Express服務器設置與HTTP和HTTPS和CORS問題

app.use(function (request, response, next) { 
    response.header('Access-Control-Allow-Origin', '*'); 
    response.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); 
    response.header(
    'Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, X-Api-Key' 
); 

    next(); 
}) 

app.options('*', function (request, response) { 
    response.send(200); 
}); 

app.listen(httpPort, function() { 
    console.log('Listening on port: ' + httpPort); 
}); 

httpsServer = https.createServer(credentials, app); 
httpsServer.listen(httpsPort, function() { 
    console.log('Listening on port: ' + httpsPort); 
}); 

我也不得不enpoints: https://local:8000http://local:8001

在那一刻我想請撥打電話http://local:8001https://local:8001/api,但得到CORS問題:

跨源請求被阻止:相同來源策略不允許在0123讀取遠程資源。這可以通過將資源移動到相同的域或啓用CORS來解決。

在Chrome我越來越:

的XMLHttpRequest無法加載https://local:8000/。請求的資源上沒有「Access-Control-Allow-Origin」標題。因此'Origin'http://local:8001'不允許訪問。

如何使用Express服務器上CORS

回答

0

這個整理我的問題排序問題:

app.use(function(req, res, next) { 
    res.header('Access-Control-Allow-Origin', 'http://local:8001'); 
    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, X-Api-Key' 
); 
    res.header('Access-Control-Allow-Credentials', 'true'); 
    if ('OPTIONS' === req.method) { 
    res.sendStatus(200); 
    } 
    else { 
    next(); 
    } 
});