1

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

2
  • What you want to do is unclear. Do you want to return a json from your node app only containing the elements containing the role property? Commented Sep 2, 2018 at 11:43
  • I want to return every elements that is stored in JSON file.. Commented Sep 2, 2018 at 11:44

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

You might mention the need to parse it client side
Updated my answer. Thanks. :)
Thanks for answer but man i am little confused all i want to do is returning every json data that is currently stored in user.json to the client.. is that the quick and simple way to do ??? sorry to ask you silly question..
Yeah that's the method that I've told you about in the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.