How to enable CORS in MEAN STACK web app?

前端 未结 2 925
感动是毒
感动是毒 2020-12-21 00:56

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 cus

相关标签:
2条回答
  • 2020-12-21 01:58

    If you only have one Express server, you only need to add the middleware once. Your other modules are probably provided as middleware to the server.

    If you register a middleware function without any qualifying path, like app.use(function(){ ... }), the middleware will run for every request processed by the server. It does not matter what other middleware is invoked by any given request.

    If you have multiple Express servers running simultaneously (this is fairly unlikely), then you will need to add the middleware to each server.

    0 讨论(0)
  • 2020-12-21 02:02

    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);
    
    0 讨论(0)
提交回复
热议问题