简体   繁体   English

如何发送从文件读取的数据作为 NodeJS 中快速路由的响应?

[英]How to send data read from file as response from an express route in NodeJS?

I have a JSON file in local folder with a structure like this.我在本地文件夹中有一个 JSON 文件,其结构如下。

{
   license: "abcd",
   name: "abcd",

   data: [
      Array of JSON Objects ....
   ]
}

I want to access the data array in the Object and send it as response from express route This is what I tried.我想访问对象中的数据数组并将其作为快速路由的响应发送这是我尝试过的。

import express from "express";
import fs from "fs";
import bodyParser from "body-parser";

var app = express();
app.use(bodyParser.json());

var fileData: string = fs.readFileSync("path to json file", { encoding: 'utf-8' });
var jsonData = JSON.parse(fileData).data;

console.log(jsonData);

app.get("/getJsonData", (err, res) => {
    if (err)
        throw err;

    res.send(JSON.stringify(jsonData));
});

app.listen("3001", () => console.log("listening at 3001"));

It shows correct json when I log it outside the express route function, but inside the function the response is [object Object] with status code of 500 (Internal Server Error).当我在快速路由函数之外记录它时,它显示正确的 json,但在函数内部,响应是 [object Object],状态代码为 500(内部服务器错误)。

I tried the asynchronous method also我也尝试了异步方法

var app = express();
app.use(bodyParser.json());

app.get("/getJsonData", (err, res) => {
    if (err)
        throw err;

    fs.readFile("path to json file", (fileErr, result) => {
        if(fileErr) throw fileErr;

        var jsonData = JSON.parse(result.toString()).data;

        res.json(jsonData);
    });
    
});

but I get the same response as [object Object] and status code 500. I tried res.send(JSON.stringify(jsonData)) but no use.但我得到与 [object Object] 和状态码 500 相同的响应。我尝试res.send(JSON.stringify(jsonData))但没有用。 How can I send the json data that I get from file to frontend using Express??如何使用 Express 将我从文件中获取的 json 数据发送到前端? btw I am using TypeScript for this.顺便说一句,我为此使用 TypeScript。

This line这条线

app.get("/getJsonData", (err, res) => 

The err is not an error, its the request it should be: err不是错误,它应该是请求:

app.get("/getJsonData", (req, res) => {
    res.send(JSON.stringify(jsonData));
});

Its literally at the example Hello world site of express.js, there you will sees that they use req它的字面意思是 express.js 的示例Hello world站点,在那里你会看到他们使用req

https://expressjs.com/de/starter/hello-world.html https://expressjs.com/de/starter/hello-world.html

The reason why you always get an 500 error is because err , wich is obviously the request, is always truthy你总是得到 500 错误的原因是因为err ,这显然是请求,总是真实的

You also dont need to Stringify it, you could just do res.json(jsonData)你也不需要字符串化它,你可以做res.json(jsonData)

If you want to send a json object between your express server and the client, you'll need to send the data via res.json(obj) where obj must explicitly be a JSON object (can't be an array of JSON objects).如果要在快速服务器和客户端之间发送 json 对象,则需要通过res.json(obj)发送数据,其中 obj 必须明确是 JSON 对象(不能是 JSON 对象数组) . What you can do to just send the array, is simply wrap your jsonData array inside a bracket pair and you are done.您可以做的只是发送数组,只需将您的 jsonData 数组包装在一个括号对中,您就完成了。

let jsonData = JSON.parse(fileData).data;
res.json({ jsonData });
//or if you dont understand the above use
res.json({ jsonData: jsonData})
//which is equivalent to the above line

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 nodejs express 发送响应到 angular 应用程序 - send response from nodejs express to angular app 如何从后端(快递)在nodeJS中创建html文件并将其发送到客户端? - How to create and send html file to client in nodeJS from backend(express)? 从Express发送JSON数据到HTML NodeJS - Send JSON data from express to html NodeJS 从NodeJS发送文件作为对Jquery AJAX的响应 - Send a file from NodeJS as response to Jquery AJAX 如何从POST读取数据,使用条件进行测试并发送回响应 - How to read data from POST, test it with a condition and send a response back 如何从服务器路由到javascript获取数据? Nodejs Express哈巴狗 - How do I get data from server route to javascript? Nodejs Express pug 如何在nodejs / express中异步发送响应 - How to send response asynchronously in nodejs / express 如何使服务器中的快速路由等到它收到来自另一个nodejs进程的套接字io消息,然后再向客户端返回响应? - how to make express route in server wait until it receives a socket io message from another nodejs process before returning response to client? 如何从Express路由提供脚本文件 - How to serve script file from Express route 从服务器向客户端发送数据。 节点JS,快递 - Send data from server to client. NodeJS, Express
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM