我正在尝试从主应用程序到外部角度应用程序获取频道列表。
我已将https://github.com/stubailo/meteor-rest/blob/master/packages/rest/README.md添加到我的主流星应用程序中,现在我可以使用json格式的网址获取该集合。
现在当我尝试从外部角度应用程序发出http请求时出现问题。
这是我在主流星应用程序中的内容:
'use strict'
Meteor.publish('channels', function (index) {
return Channels.find({});
}, {
url: 'channels',
httpMethod: 'get'
});
这是我用来在外部角度应用程序中发出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 cannot load http://example.com/channels. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
我该怎么做才能解决这个问题?
答案 0 :(得分:3)
来自meteor-rest套餐的documentation:
如果您想从其他应用的客户端使用您的API,则需要返回一个特殊标头。您可以通过挂钩
simple:json-routes
包上的方法来完成此操作,如下所示:
// 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"
});