2017-02-28 111 views
0

承担任何错误/错误的术语,因为我是新手。我使用流星来开发我的项目,我需要向外部API发出请求。 (我已经加meteor add http)下面是我的代码:流星获取请求

HTTP.call('GET', 'url', {}, function(error, response) { 
    if (error) { 
    console.log(error); 
    } else { 
    console.log(response); 
    } 
}); 

如果我在流星使用我的客户端文件夹内的代码,我收到以下错误No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access meteor它是与CORS我不明白如何实行。如果我在服务器端使用上面的代码,我确实在控制台中得到了正确的响应,但是如何在客户端JavaScript代码中将它用作var?

+0

其到服务提供商以启用CORS,但也有方法,你可以尝试破解它周围(但它不漂亮)。我建议你只需从Meteor方法中的服务器执行你的调用,然后从你的Meteor客户端代码中调用该方法。简单,简单,直接。 – jordanwillis

回答

0

修正了它。在客户端

Meteor.call("getURL",'url',{},function(err,res){ 
    if(err){ 
     console.log('Error: '+err); 
    } 
    if(!err){ 
    console.log('Response: '+res); 
     } 

和服务器

Meteor.methods({ 
    'getURL': function(url_l){ 
    console.log("Request: "+url_l) 
    return HTTP.get(url_l) 
    } 
}); 
+2

请注意,这会造成一个安全漏洞,任何人都可以让您的服务器根据需要随时多次致电* any * url。 –

0

头可以使用。调用HTTP的功能,并通过你的头在选项:

HTTP.call(method, url, [options], [asyncCallback]) 

参数

方法字符串

The HTTP method to use, such as "GET", "POST", or "HEAD". 

URL字符串

The URL to retrieve. 

的AsyncCallback功能

Optional callback. If passed, the method runs asynchronously, instead of synchronously, and calls asyncCallback. On the client, this callback is required. 

选项

内容字符串

String to use as the HTTP request body. 

数据对象

JSON-able object to stringify and use as the HTTP request body. Overwrites content. 

查询字符串

Query string to go in the URL. Overwrites any query string in url. 

PARAMS对象

Dictionary of request parameters to be encoded and placed in the URL (for GETs) or request body (for POSTs). If content or data is specified, params will always be placed in the URL. 

权威性字符串

HTTP basic authentication string of the form "username:password" 

对象

Dictionary of strings, headers to add to the HTTP request. 

超时

Maximum time in milliseconds to wait for the request before failing. There is no timeout by default. 

followRedirects布尔

If true, transparently follow HTTP redirects. Cannot be set to false on the client. Default true. 

npmReq uestOptions对象

On the server, HTTP.call is implemented by using the npm request module. Any options in this object will be passed directly to the request invocation. 

beforeSend功能

On the client, this will be called before the request is sent to allow for more direct manipulation of the underlying XMLHttpRequest object, which will be passed as the first argument. If the callback returns false, the request will be not be send. 

周守军:Here