如何将获取响应数据从获取API发送到客户端?

时间:2019-07-14 08:29:50

标签: javascript node.js express client-server fetch-api

有一个json对象,我使用访存API进行了API调用,并且得到了预期结果的响应。如何将结果发送到客户端,以便能够在界面中显示它们?我使用了Node.js的express模块​​。

const fetch = require("node-fetch");
const express = require("express");
var bodyParser = require('body-parser');
const app = express();
app.post('/', (req, res) => {
res.sendStatus(200);



jsonBody = JSON.parse(fs.readFileSync("./resources/jsonBody.json", {
    encoding: 'utf8'
}));



function results() {
    fetch(url, {
        method: 'POST',
        body: JSON.stringify(jsonBody),
        headers: {
            "Authorization": "Bearer " + predictionKey,
            "Content-Type": "application/json"
        },
    }).then(response => response.json()).then(response => 
                 console.log(response.Results.output1.value.Values));


}

results()


})


});

客户端发布功能:

function postMessage(message){
  $.post("http://localhost:8000",message);
}

这是服务器上api调用的响应

[ [ '1008', '0', '1' ],
  [ '1079', '1', '3' ],
  [ '1022', '2', '3' ] ]

我想在界面上(客户端上)显示这些值

1 个答案:

答案 0 :(得分:0)

您在提取中使用的变量url没有在任何地方定义,因此我必须假定您在要调用的API的其他位置有一个全局变量。

如果是这样,则说明您不按顺序执行此操作-发送一个空的200 OK,然后获取jsonBody(这是另一个全局变量,可能是无意的),但是从不使用这些结果。

尝试像这样重新排列:

const fetch = require("node-fetch");
const express = require("express");
var bodyParser = require('body-parser');
const app = express();
app.post('/', (req, res) => {
  res.sendStatus(200);

  var jsonBody = JSON.parse(fs.readFileSync("./resources/jsonBody.json", {
    encoding: 'utf8'
  }));

  fetch(url, {
    method: 'POST',
    body: JSON.stringify(jsonBody),
    headers: {
      "Authorization": "Bearer " + predictionKey,
      "Content-Type": "application/json"
    },
  }).then(response => response.json()).then(response => { 
    console.log(response.Results.output1.value.Values);
    res.json(response.Results.output1.value.Values); // or whatever you want from response
  });
});
相关问题