简体   繁体   中英

Enable cross-origin resource sharing in Meteor?

I'm trying to get a list of channels from my main application to an external angular app.

I've added https://github.com/stubailo/meteor-rest/blob/master/packages/rest/README.md to my main meteor app and now I can get the collection with a url as json format.

Now the problem comes when I try to http request from the external angular app.

Here's what I have in my main meteor app:

'use strict'

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

and here's what I use to make the http request in the external angular app:

// 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);
  });

But what I get in response is an error:

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.

What can I do to fix this?

From the documentation on the meteor-rest package:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM