I try to return the data in JSON through REST API.

Node JS + Express Js

server.js

var userController = require('./UserController'); app.route('/api/users') .get(userController.getUsers); 

UserController.js

 var userModel = require('./User'); function getUsers() { return JSON.parse(userModel); } 

User.js

 var users = []; users.push({id: "1", username: "regular", password: "user", role: "1"}); users.push({id: "2", username: "premium", password: "user", role: "2"}); 

Mistake

 undefined:1 [object Object],[object Object] ^ SyntaxError: Unexpected token o in JSON at position 1 

I know that there are objects inside, but how can I return JSON to the client?

  • Is [object Object],[object Object] - JSON ? - vp_arth

2 answers 2

Your users not json , but an array. It no longer needs to parse:

 var userModel = require('./User'); function getUsers() { return userModel; } 

    As an option - to check whether the model comes already in the form of JSON. If yes, then return immediately. If not, then parse and return.

     function getUsers() { return typeof userModel === "string" ? JSON.parse(userModel) : userModel; } 
    • Comment on both answers above. if return return userModel; as it is, I get the error Error: Route.get () requires callback functions - [Undefined] - Sergei R