简体   繁体   English

如何在浏览器中打印 json console.log 数据以与 api 一起使用

[英]How to print json console.log data in browser for use with api

Okay... I would like to create an api but i cant seem to output the data, i have parsed it from an xml file and can console.log the necessary data but when i want to output the data to the browser i just get an empty array any suggestions?好的...我想创建一个 api 但我似乎无法输出数据,我已经从 xml 文件中解析了它并且可以在 console.log 中记录必要的数据但是当我想将数据输出到浏览器时我只是得到一个空数组有什么建议吗?

const express = require('express');
const app = express();
const fs = require('fs');
const xmlParser = require("xml2json")

app.get('/posts', (req, res) => {
        
        let xmin = req.query.xmin;
        let xmax = req.query.xmax;
        let ymin = -Math.abs(req.query.ymin);
        let ymax = -Math.abs(req.query.ymax);
        
        

        const foodRatings = fs.readFile( "./FHRS433en-GB.xml", function(err, data) {
            const xmlObj = xmlParser.toJson(data, {reversible: true, object: true})
            const estDetail = xmlObj["FHRSEstablishment"]['EstablishmentCollection']['EstablishmentDetail']
            
            
            for (let i=0;i < estDetail.length;i++) {
                let latitude = estDetail[i]["Geocode"]["Latitude"]
                let longitude = estDetail[i]["Geocode"]["Longitude"]
                if ((typeof latitude !== "undefined") && (typeof longitude !== "undefined")) {
                        if ((latitude['$t'] >= xmin && latitude['$t'] <= xmax) && (longitude['$t'] >= ymin && longitude['$t'] <= ymax)) {
                            // jsonData += estDetail[i];
                            let jsonData = [];
                            var config = JSON.parse(estDetail[i]);
                            jsonData.push(config);
                            console.log(jsonData);
                            res.json(jsonData);
                        } 
                } 
            }
        })
}); 

When i see people outputting the data online they have the json data in an object which links directly to the string not a file, i dont know how i would go about extracting the data from the file passing it into an empty array then which i can call the data using res.json(jsonData)?当我看到人们在线输出数据时,他们将 json 数据放在一个对象中,该对象直接链接到字符串而不是文件,我不知道如何从文件中提取数据并将其传递到一个空数组中,然后我可以使用 res.json(jsonData) 调用数据?

Thank you in advance先感谢您

did u try to你试过吗

return res.json(data)

I see you are in a for loop, so probably you want to do that outside of it我看到你在 for 循环中,所以可能你想在它之外做

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM