Jay
Jay

Reputation: 87

JSON with angular and node.js

Hi guys I am very new to node JS and angular. I am currently working on some handling JSON file with Angular and Node JS but unfortunately, I faced a problem at the moment. I am trying to return all of the JSON elements(key&value) once it is called. For example, some JSON element has key named 'role' and some of them are not so I want to retrieve all of them first then deal with that... please help me

JSON file

{"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;
        }
    });
}

ajax

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

I am using ajax.. so I want to receive the data

Upvotes: 1

Views: 620

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39432

You don't have to do this: worker_with_role = JSON.parse(data);

JSON.parse converts stringified JSON into a JSON Object. And you can't send JSON Objects to the response. It should be 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();
      }
    });
  }
}

On the client when you receive this, you can then parse it there to convert it into a JSON Object. Although Angular's HttpClient does that automatically for you.

Update:

If you're using Angular, please don't use jQuery to make AJAX Calls. That just beats the whole purpose of using Angular in the first place.

Use HttpClient instead.

Upvotes: 3

Related Questions