繁体   English   中英

如何将数据从 nodejs 使用的 api 返回到前端?

[英]How to return data from an api consumed by nodejs to the frontend?

我试图使用的 API 来自第三方,它阻止了跨域,所以我不能用 jquery 或 javascript 来使用它......所以我不得不在 nodejs 中创建一个脚本来使用这个 API......

我想知道如何使用 nodejs 从 API 获取到我的前端的数据,使用 javascript?

请记住,此 nodejs 与我的前端位于一个单独的文件中,并在另一台服务器上运行。

var request = require("../../node_modules/request");
var options = { method: 'GET',
  url: 'https://....apimanagement.us2.hana.ondemand.com/bot/v1/...',
  qs: { Shop: '..'', PeriodoAte: '...' },
  headers: 
   { 'postman-token': '822e513f-da5e-4a0b-b403-1dd8fa46e86f',
     'cache-control': 'no-cache',
     authorization: 'Basic .........',
     apikey: '....',
     'content-type': 'application/json' },
  json: true };

request(options, function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

您需要一个 Web 服务器侦听请求,以便将前端与后端 (Node.js) 进行通信。 如果你想要一些简单的东西,你可以使用Express 您也可以使用 JavaScript 框架,有很多( Sails.js是快速入门的好选择)。

如果您无法在服务器中安装 Node.js,另一种选择是使用 AWS Lambda 快速创建一个 API,您可以通过 HTTP 请求从前端使用该 API。

一种路径是:

  • 选择一个节点框架(Express,Hapi,...)让我们为这个例子选择 Hapi
  • 阅读入门指南https://hapijs.com/tutorials/getting-started
  • 了解 Promise 或经历回调地狱
  • 最终得到这样的东西进行测试

    'use strict'; const Hapi = require('hapi'); const rp = require('request-promise'); const server = Hapi.server({ port: 3000, host: 'localhost' }); server.route({ method: 'GET', path: '/', handler: (request, h) => { const options = { method: 'GET', uri: 'https://./..', qs: {Shop: '..', PeriodoAte: '...'}, headers: { 'postman-token': '822e513f-da5e-4a0b-b403-1dd8fa46e86f', 'cache-control': 'no-cache', authorization: 'Basic .........', apikey: '...', 'content-type': 'application/json' }, json: true }; return rp(options).catch(e => { console.log(`api call failed ${e}`); return 'fail'; }) } }); const init = async () => { await server.start(); console.log(`Server running at: ${server.info.uri}`); }; process.on('unhandledRejection', (err) => { console.log(err); process.exit(1); }); init();
  • 现在你可以用 node 启动它并访问 'localhost:3000/'

  • 阅读更多,尝试更多
  • 阅读节点生产模式和托管

类似的东西,希望它有点帮助

编辑: //

在客户端上消费只需使用例如 jquery 来获取上面代码提供的路由

以下是评论中要求的一些客户端示例:

如果您从其他位置提供 html,而不是 hapi api,则需要在 HapiJS 路由中启用 cors。

     server.route({
        method: 'GET',
        path: '/',
        config: {
            cors: {
                origin: ['*'],
                additionalHeaders: ['cache-control', 'x-requested-with']
            }
        },

那么使用这个端点的一种方法是 jquery

   <!doctype html>
    <html>
    <head>
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    </head>
    <body>
    <input type="button" id="Button" value="Fetch"/>
    <div id='main'></div>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#Button').click(() => {
                $.ajax({
                    url: "http://localhost:3000/info", success: (result) => {
                        $("#main").text(result);
                    }
                });
            });
        });
    </script>
    </body>
    </html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM