我有一个不支持 CORS 的第 3 方 JSON 端点,我已经知道我的应用程序应该通过服务器代理请求。我今天研究了几个小时,但没有看到一个简单的解决方案(几个复杂的解决方案......)。
所以基本上我需要做类似 request( 'http://localhost:3000/publications/jsonProxy' )
的事情,它调用 Meteor 服务器。然后,我需要一个使用安全 token 从第三方请求数据的发布,并且我需要将该数据返回到浏览器。
我尝试过类似的事情:
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
。这可能不太接近正确的方法,我有点迷失了。
看起来很简单,谁能指出我将这些数据返回到浏览器的正确方法?
最佳答案
看起来我已经成功了。下面的示例代码,不是“真实”代码,因为我必须断章取义。
/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
文件夹中是否重要,但是嘿,它正在工作,我还有更多东西要构建。
关于javascript - 如何使用 Meteor JS Node 服务器代理第 3 方 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38678175/