如何在快递应用程序中为预检请求设置Access-Control-Allow-Origin标头

时间:2018-01-20 15:37:29

标签: angularjs node.js express cors

我有一个角度4的应用程序,它在我的开发机器上从服务到快速api发出以下请求。

get_currencies_url = "http://localhost:3002/currencies";

getCurrencies(): Observable<Currency[]>{
  return this.http.post(`${this.get_currencies_url}`, {})
  .map(res  => {
    //Maps the response object sent from the server
    return res["result"] as Currency[];
  })
}

快递应用程序index.js文件具有以下代码

var express = require('express');
const bodyParser = require('body-parser');

/*initializations*/
global.mongoose = require('mongoose');
global.app = express();
global.config = require('./config/config');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));//accept strings, arrays   and any other type as values
var cors = require('cors')
app.disable('x-powered-by');

//DB connection
app.listen(config.port, function(){
console.log("Express started on " +config.base_url +' in '+config.env +' environment. Press Ctrl + C to terminate')
global.db = mongoose.connect(config.db.uri)
});

//CORS configuration
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:4200");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
 });

require('./routes/user.routes'); 

user.routes的内容是

app.post('/currencies', function(req,res,next){
   let rawdata = fs.readFileSync('./data/currencies.json');  
   let currencies = JSON.parse(rawdata);  
   res.send(currencies);
})

我正在使用chrome a

 "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 501." 

发出请求时出错,您可以看到我已尝试设置&#34; Access-Control-Allow-Origin&#34;标题允许我的角度应用程序的跨域请求。似乎问题来自于预检OPTIONS请求服务器没有处理。不知道此刻该怎么做。

如何设置服务器以处理OPTIONS请求。

0 个答案:

没有答案