Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angularjs - How to enable CORS in MEAN STACK web app?

I am working on a MEAN-STACK application.Using Mean-cli packgae of node. in which i am using darksky weather API, in package name Information. I have 4 other packages in custom folder of mean app. how did i enable the CORS so that all API request did not fail and return the response.

i googled and find out that i have to add this middleware.

 //CORS middleware
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'example.com');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
}

where should i add this. in each package where we are using cross-origin request or in some global file.

I have tried to add this middleware in server -route file of ? Information package and in express.js file of confile but it didn't work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So the actual solution to your issue turned out to be using jsonp callback with forecast.io api as they haven't enabled CORS headers for client access. Use $http.jsonp like this

$http.jsonp(url + lat + ',' + lng + '?callback=JSON_CALLBACK');

In general to enable CORS on your expressjs server do the following.

  1. Install cors module for express with npm install cors
  2. require it var cors = require('cors');
  3. Set it on your express app instance with app.use(cors());

cors module will automatically add all aors related headers on the response. Alternately you could also configure a lot of options. Check the official docs

OR

If you want to do it yourself you could do the following

var permitCrossDomainRequests = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
// some browsers send a pre-flight OPTIONS request to check if CORS is enabled so you have to also respond to that
if ('OPTIONS' === req.method) {
  res.send(200);
}
else {
  next();
}
};

then Enable your CORS middleware

app.use(permitCrossDomainRequests);

Enable routes at the end

app.use(app.router);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...