javascript - 使用 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
}
解决方案
我没有看到来自服务器的任何响应。如果你想向用户发送一些东西,你需要做一个
res.json({your json data});
这将返回对请求的 JSON 响应,此外您还可以设置响应代码等。
推荐阅读
- c - C - Struct- 指向没有强制转换的指针的整数
- servlets - request.getServletContext().getRealPath() 在 jsp servlet 中返回 null
- java - Oracle BI 报表服务返回 0 大小字节数组
- c - How to call a C DLL from a VBA application and return an array?
- javascript - 带有css的JQuery mouseleave函数错误
- javascript - 在 ES6 中创建多个构造函数
- c++ - How can I construct one map from another map?
- java - 在Java中的抽象类中获取运行时输入
- html - 悬停效果不适用于标签
- javascript - 如何仅在单击时显示元素并在单击其他元素时隐藏它?