首页 > 解决方案 > 使用 Node.js 将来自服务器端 GET 请求的响应传递给客户端

问题描述

我在网页上有一个按钮。单击按钮时,服务器端代码向内部 API 发送 GET 请求。我无法将响应传递回客户端。我可以在 Node 中记录响应 - 但客户端上的响应是空的。任何帮助,将不胜感激。

客户端

window.addEventListener('DOMContentLoaded', (event) => {
  console.log('DOM fully loaded and parsed')
  let body = document.querySelector('body')
  let h3 = document.createElement('h3')
  h3.innerText = 'ONT is on Node:'
  body.appendChild(h3)
  let button = document.createElement('button')
  button.innerText = 'Get ONT'
  body.append(button)
  button.addEventListener('click', getONT)

  async function getONT() {
    let response = await (fetch('https://ont.xxx.net/node/', ))
    .then(result => resultBody = JSON.stringify(result))
    .then(result => {console.log(resultBody)})
    .catch(error => console.log('error', error));
  }
})

服务器端

#!/usr/bin/env nodejs
var http = require('http');
var https = require('https')
var fetch = require('node-fetch')

http.createServer(function (request, response) {
  response.setHeader("Content-Type", "application/json");
  response.setHeader("Access-Control-Allow-Origin", "*");
  response.writeHead(200);
  response.end(JSON.stringify(getData()))
}).listen(8080);
console.log('Server running at http://127.0.0.1:8080/');

async function getData() {
  const smx = "https://xxx/rest/v1/ont/searchall?filter=object.ontId LIKE xxx"
  console.log(smx)
  let response = await fetch(smx, {
    method: 'GET',
    withCredentials: true,
    headers: {
      "Authorization": "Basic xxx",
      "Access-Control-Allow-Origin": "*",
      "Content-Type": "application/json"
    },
    redirect: 'follow'
  })
  let data = await response.json()
  data = JSON.stringify(data)
  console.log(typeof(data))
  return data
}

标签: javascriptapi

解决方案


我没有看到来自服务器的任何响应。如果你想向用户发送一些东西,你需要做一个

 res.json({your json data});

这将返回对请求的 JSON 响应,此外您还可以设置响应代码等。


推荐阅读