当我在服务器上执行此操作时:
app.get("/users", (req, res) => {
console.log("a get request");
var tryFetch = { myString: "I am working fetch" };
res.json(tryFetch);
});
在客户端:
class Example extends React.Component {
async componentDidMount() {
console.log("mounting...");
const response = await fetch("/users");
console.log(response, "res");
const responseJson = await response.json();
console.log(responseJson, "this is the data....");
}
场景 A) 在 /
处,浏览器是 console.logging 正确的内容,但在 /users
处,它在浏览器主体本身中显示 json。为什么?
场景B)
我在服务器上执行此操作
app.get("/users", (req, res) => {
console.log("a get request");
var getData = await fetch("https://jsonplaceholder.typicode.com/users");
var response = await getData.json();
console.log(response, "the response");
res.send(json);
});
我收到了发送到服务器的用户的正确响应,但该请求似乎需要很长时间才能完成,并且在 postman 中超时。我看不到浏览器中记录的响应。但在服务器上绝对是正确的
我的主要问题是:我是否正确地在服务器上发出了请求?以及如何让它显示在客户端上(不超时)?
最佳答案
所以问题出在服务器上
您在此处使用 res.send(json)
:
app.get("/users", (req, res) => {
console.log("a get request");
var getData = await fetch("https://jsonplaceholder.typicode.com/users");
var response = await getData.json();
console.log(response, "the response");
res.send(json); // <---
});
它的基本作用是将“json”发送回客户端,客户端只需渲染它。而是使用 res.json()
将 json 作为回复发送给客户端。
所以你想要的是:
app.get("/users", (req, res) => {
console.log("a get request");
var getData = await fetch("https://jsonplaceholder.typicode.com/users");
var response = await getData.json();
console.log(response, "the response");
res.json(response);
});
关于node.js - 如何在客户端正确显示服务器请求的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51018620/