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

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

问题描述

我正在开发一个 MEAN-STACK 应用程序.使用节点的 Mean-cli 包.我使用的是darksky天气API,在包名信息中.我在mean app的自定义文件夹中有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.

我已经尝试在 server -route 文件中添加这个中间件?信息包和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. 需要它 var cors = require('cors');
  3. 使用 app.use(cors());
  4. 在您的快速应用实例上设置它
  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 模块将自动在响应中添加所有与 aors 相关的标头.或者,您也可以配置很多选项.查看官方文档

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

如果你想自己做,你可以这样做

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 Web 应用程序中启用 CORS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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