我有一个不支持CORS的第三方JSON端点,我已经形成了我的应用程序应该通过服务器代理请求。我今天已经研究了几个小时,并没有看到一个简单的解决方案(一些复杂的解决方案......)。
所以基本上我需要做一些调用Meteor服务器的request( 'http://localhost:3000/publications/jsonProxy' )
。然后我需要一个使用安全令牌从第三方请求数据的出版物,我需要将该数据返回给浏览器。
我尝试过类似的事情:
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 :(得分: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'
<强> /imports/ui/pages/app/app.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
文件夹中,但是它正在工作,我还有更多要构建的东西。