2016-02-18 72 views
1

我試圖從我的主應用程序獲得一個通道列表到外部的角度應用程序。啓用Meteor中的跨源資源共享?

我已將https://github.com/stubailo/meteor-rest/blob/master/packages/rest/README.md添加到我的主流星應用程序中,現在我可以使用url作爲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.

我能做些什麼來連接x這個?

回答

3

documentation的流星其餘包:

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" 
}); 
+0

我在哪裏添加此代碼?它不解釋 –

+1

你應該能夠在你的服務器啓動文件中做到這一點。 –

+0

這樣做,只是將它添加到'Meteor.startup'函數。感謝您的澄清! –