javascript - 在 Meteor 中启用跨源资源共享?

标签 javascript angularjs meteor cors angular-meteor

我正在尝试获取从我的主应用程序到外部 Angular 应用程序的 channel 列表。

我添加了 https://github.com/stubailo/meteor-rest/blob/master/packages/rest/README.md到我的主要 meteor 应用程序,现在我可以使用 json 格式的 url 获取集合。

现在,当我尝试从外部 Angular 应用程序发出 http 请求时,问题就来了。

这是我的主要 meteor 应用程序中的内容:

'use strict'

Meteor.publish('channels', function (index) {
  return Channels.find({});
}, {
    url: 'channels',
    httpMethod: 'get'
});

这是我用来在外部 Angular 应用程序中发出 http 请求的方法:

// Simple GET request example:
$http.get('http://example.com/channels').then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
    console.log('success');
    console.log(response);
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
    console.log('error');
    console.log(response);
  });

但是我得到的响应是一个错误:

XMLHttpRequest 无法加载 http://example.com/channels。请求的资源上不存在“Access-Control-Allow-Origin” header 。因此不允许访问源“http://localhost”。

我该怎么做才能解决这个问题?

最佳答案

来自documentation在 meteor-rest 包上:

If you would like to use your API from the client side of a different app, you need to return a special header. You can do this by hooking into a method on the simple:json-routes package, like so:

// Enable cross origin requests for all endpoints
JsonRoutes.setResponseHeaders({
  "Cache-Control": "no-store",
  "Pragma": "no-cache",
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET, PUT, POST, DELETE, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With"
});

关于javascript - 在 Meteor 中启用跨源资源共享?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35492462/

相关文章:

javascript - 尽管选择器键为空,发布中的 Meteor find() 仍返回数据

javascript - javascript中的正则表达式问题

javascript - GTM : collect coordinates (x, y) 来自事件

javascript - 使用 onComplete 按顺序执行 Fabric.js 动画

javascript - Meteor JS 模板事件使用 jquery 替换文本

javascript - 安全 header 在 PayPal Mass Payments 中无效

javascript - 如何使用 jest 的参数测试请求 http - Angular

AngularJs:深层链接默认 Index.Html 未打开

javascript - 外部点击在 angularjs 中不起作用

angularjs - 设置 reloadOnSearch=false 时如何在 angular-ui-router 中查看状态参数