javascript - 如何在 Sails.js 中为自定义路由启用 CORS

标签 javascript angularjs node.js cors sails.js

我有一个 Angular 1.x 应用程序可以在我的 Sails.js 应用程序中调用 API。每当我尝试从我的 Angular 应用程序调用 API 时,我都会得到这个 -

XMLHttpRequest cannot load <a href="http://localhost:1337/portal/login" rel="noreferrer noopener nofollow">http://localhost:1337/portal/login</a>. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains the invalid value ''. Origin '<a href="http://localhost:8080" rel="noreferrer noopener nofollow">http://localhost:8080</a>' is therefore not allowed access.

由于我的 Sails.js 应用程序有很多其他 API,这些 API 不会在此 Angular 应用程序上使用,我不想通过设置 allRoutes: true 对所有这些应用程序应用 CORS。在配置/cors.js 中。所以我遵循了 Sails.js 的文档并以这种方式编写了自定义 CORS 配置 -

    '/portal/login': {
        target: 'MyController.login',
        cors: {
            origin: '*',
            credentials: true,
            methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH',
            headers: 'content-type, Authorization'
        }
    }

但它不起作用。如果我启用 allRoutes: true然后它开始工作,但我不想在我的所有路线上启用 CORS 并公开它们。我已经尝试了所有可能的组合 origin, credentials, methods, headers但它总是给出相同的错误。

你能帮我解决这个问题吗? 提前致谢。

最佳答案

/config/http.js 文件中,取消注释 'order' 数组片段并在 myRequestLogger 方法中添加 header 参数。

order: [
  'startRequestTimer',
  'cookieParser',
  'session',
  'myRequestLogger',
  'bodyParser',
  'handleBodyParserError',
  'compress',
  'methodOverride',
  'poweredBy',
  '$custom',
  'router',
  'www',
  'favicon',
  '404',
  '500'
],


 myRequestLogger: function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
  res.header('Allow', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
  res.header('X-Powered-By', '');
  return next();
},

/config/cors.js (sails v0.12) 或 /config/security.js (sails v1.x) 中添加以下代码片段

module.exports.security = { //sails v1.x, if is sails v0.12 change security for cors
  allRoutes: true,
  allowOrigins: '*',
  allowCredentials: false,
  allowRequestMethods: 'GET,POST,PUT,DELETE,OPTIONS,HEAD',
  allowRequestHeaders: 'content-type'
}

如果这些都不起作用(我发现这很难发生),请添加您的 controller 方法的返回值(但是,我认为没有必要):

return res.set({
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
  }).json({ status: true, //body });

关于javascript - 如何在 Sails.js 中为自定义路由启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41671082/

相关文章:

ruby-on-rails - Ruby 和客户端 JS 的模板语言

javascript - ng-show 不只在加载时运行动画

angularjs - View 中的小写数据绑定(bind)值

javascript - AngularJS 组件之间的绑定(bind)不起作用

node.js - 使用 Docker 运行单个 NodeJS 脚本并能够使用 Ctrl-C 终止它的最简单方法是什么

c++ - 如何安装opencv4nodejs模块

javascript - 如何根据单选按钮切换启用/禁用输入字段

javascript - 后增量和加法

javascript - PDFMAKE 未生成 pdf 水印

node.js - 如何在 node.JS 项目上使用 Cassandra CLI?