【问题标题】:How can I send the serve response data from a fetch API to client?如何将服务响应数据从 fetch API 发送到客户端?
【发布时间】:2019-11-23 07:56:14
【问题描述】:

拥有一个 json 对象,我使用 fetch 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' ] ]

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

【问题讨论】:

  • 你能添加更多关于客户的细节吗?它是什么类型的客户?在界面上显示值是什么意思?

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


【解决方案1】:

您在 fetch 中使用的变量 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
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多