2016-07-30 73 views
1

我有第三方JSON端点不支持CORS,我已经形成我的应用程序应通过服务器代理请求。我今天已经研究了几个小时,并没有看到一个简单的解决方案(几个复杂的解决方案......)。如何使用流星JS节点服务器代理第三方AJAX请求

所以基本上我需要做一些类似于request('http://localhost:3000/publications/jsonProxy')的调用Meteor服务器。然后,我需要一个发布,使用安全令牌向第三方请求数据,并且我需要将该数据返回给浏览器。

我已经尝试这样的:

const request = require('request'); 

if (Meteor.isServer) { 
    Meteor.publish('jsonProxy', function jsonProxyPublication() { 
    var options = { 
     url: 'https://somewhere.com/api/endpoint', 
     headers: { 
     'API-Key': '123' 
     } 
    }; 

    function callback(error, response, body) { 
     if (!error && response.statusCode == 200) { 
     let info = JSON.parse(body); 
     console.log(info); 
     return info 
     } else { 
     console.error(error, response) 
     } 
    } 

    request(options, callback); 

    return this.ready() 
    }); 
} 

然后:curl localhost:3000/publications/jsonProxy。这可能不是正确的做法,我有点失落。

似乎很简单,任何人都可以点我正确的方式来获取这些数据回浏览器?

+0

更新 - 我想通了,很快就会发布 – BradGreens

回答

1

看起来像我得到它的工作。下面的示例代码,不是“真实”的代码,因为我不得不从上下文中提取它。

/server/proxy/json-api.js

import { Meteor } from 'meteor/meteor'; 
import { HTTP } from 'meteor/http' 

Meteor.methods({ 
    'jsonProxy'() { 
    const apiUrl = 'https://api.com/api' 

    const response = HTTP.get(apiUrl, { 
     headers: { 
     'API-Key': '123' 
     } 
    }).data 

    console.log(`${ apiUrl } response:`, response) 

    return response 
    } 
}) 

/server/main.js

import './proxy/jsonodds.js' 

/进口/ UI /网页/应用程序/应用程序。 js

Meteor.call('jsonProxy', (error, result) => { 
    if(!error) { 
    Session.set('jsonData', result) 

    } else { 
    Session.set('jsonData', `Error: ${ JSON.stringify(error) } `) 
    } 
} ) 

Template.app.helpers({ 
    jsonData() { 
    return Session.get('jsonData') 
    } 
}) 

/imports/ui/pages/app/app.html

<template name="app"> 
    <div id="app"> 
    {{#each jsonData}} 
     {{> itemTemplate}} 
    {{/each}} 
    </div> 
</template> 

<template name="itemTemplate"> 
    <p>{{displayName}}</p> 
</template> 

编辑:我不知道,如果它的事项代理是在server文件夹,但嘿它的工作,我有更多的事情建立。

+0

[这个解决方案](https://stackoverflow.com/a/45957165/1177832)使用'WebApp'模块定义服务器路由要干净得多。 – danwild