带有angular和node.js的JSON

问题描述 投票:1回答:1

大家好我是节点JS和角度的新手。我目前正在处理一些使用Angular和Node JS处理JSON文件但不幸的是,我目前遇到了一个问题。我试图在调用后返回所有JSON元素(键和值)。例如,一些JSON元素的键名为'role',其中一些不是,所以我想先检索所有这些然后处理它...请帮帮我

JSON文件

{"name":"Manager"},
{"name":"Brad","role":"chef"},
{"name":"Edward","role":"chef"},
{"name":"Kim","role":"waiter"},
{"name":"Park"}

check.js

module.exports = function(app,fs) {
    app.get('/check', (req, res) => {

        var worker_with_role = [];

        fs.readFile('user.json', 'utf8', function(err, data) {
            worker_with_role = JSON.parse(data);
            res.send(worker_with_role);
            return;
        }
    });
}

阿贾克斯

function list() {
    $.ajax({
        url: window.location + '/check',
        type: 'get',
        success: function(response) {
            console.log(response);
        });
}

我正在使用ajax ..所以我想收到数据

javascript ajax angular
1个回答
3
投票

你不必这样做:worker_with_role = JSON.parse(data);

JSON.parse将字符串化的JSON转换为JSON Object。并且您无法将JSON对象发送到响应。它应该是stringified/serialized

module.exports = function(app, fs) {
  app.get('/check', (req, res) => {
    var worker_with_role = [];
    fs.readFile('user.json', 'utf8', function(err, data) {
        res.writeHead(200, {
          'Content-Type': 'application/json'
        });
        res.write(data);
        res.end();
      }
    });
  }
}

在收到此内容的客户端上,您可以在那里解析它以将其转换为JSON对象。虽然Angular的HttpClient会自动为你做这件事。

更新:

如果您使用的是Angular,请不要使用jQuery进行AJAX调用。这只是首先击败了使用Angular的全部目的。

请改用HttpClient

© www.soinside.com 2019 - 2024. All rights reserved.