2015-02-11 107 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(); 
    } 
});