【问题标题】:How to use Meteor JS Node server to proxy a 3rd party ajax request如何使用 Meteor JS 节点服务器代理 3rd 方 ajax 请求
【发布时间】:2016-12-05 07:31:40
【问题描述】:

我有一个不支持 CORS 的第 3 方 JSON 端点,我已经知道我的应用程序应该通过服务器代理请求。我今天已经研究了几个小时,但没有看到一个简单的解决方案(几个复杂的解决方案......)。

所以基本上我需要做一些类似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。这可能不是正确的方法,我有点迷茫。

看起来很简单,谁能指出将这些数据返回到浏览器的正确方法?

【问题讨论】:

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

标签: javascript meteor http-proxy


【解决方案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 文件夹中是否重要,但嘿,它正在工作,我还有更多东西要构建。

【讨论】:

  • This solution 使用WebApp 模块来定义服务器路由要干净得多。
猜你喜欢
  • 2015-10-29
  • 1970-01-01
  • 2023-02-21
  • 1970-01-01
  • 1970-01-01
  • 2017-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多