如何在MEAN STACK网络应用中启用CORS? [英] How to enable CORS in MEAN STACK web app?

查看:63
本文介绍了如何在MEAN STACK网络应用中启用CORS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发MEAN-STACK应用程序.使用node的Mean-cli packgae. 在其中我使用Darksky Weather API, 在包名称信息中.我在平均值应用程序的自定义文件夹中还有其他4个软件包. 我如何启用CORS,以便所有API请求均不会失败并返回响应.

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.

我已尝试在服务器路由文件?中添加此中间件?信息包和confile的express.js文件中,但是没有用.

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.

推荐答案

因此,针对您的问题的实际解决方案原来是将jsonp回调与Forecast.io api结合使用,因为它们未启用用于客户端访问的CORS标头.像这样使用$http.jsonp

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');

通常要在expressjs服务器上启用CORS,请执行以下操作.

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

  1. 安装 cors 模块以使用npm install cors
  2. 进行快递
  3. 要求它var cors = require('cors');
  4. 使用app.use(cors());
  5. 在您的快速应用实例上进行设置
  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模块将自动在响应中添加所有与aor相关的标头.或者,您也可以配置很多选项.检查官方文档

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();
}
};

然后启用您的CORS中间件

then Enable your CORS middleware

app.use(permitCrossDomainRequests);

在末尾启用路线

app.use(app.router);

这篇关于如何在MEAN STACK网络应用中启用CORS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆