0

I have a json string (coming from my Rails app):

http://localhost:3000/employees/1.json

How do I get my Node.js app to consume this data?

This is the code I have in my Node.js app right now:

var employees = JSON.parse("http://localhost:3000/employees.json")

This is the error I'm getting:

prompt$ node app.js
node.js:201
 throw e; // process.nextTick error, or 'error' event on first tick
 ^
SyntaxError: Unexpected token h
 - at Object.parse (native)
 - at Object. (/Documents/Coding/dustin/employees.js:19:22)
 - at Module._compile (module.js:441:26)
 - at Object..js (module.js:459:10)
 - at Module.load (module.js:348:31)
 - at Function._load (module.js:308:12)
 - at Module.require (module.js:354:17)
 - at require (module.js:370:17)
 - at Object. (/Documents/Coding/dustin/app.js:34:17)
 - at Module._compile (module.js:441:26)
Kev
120k53 gold badges308 silver badges396 bronze badges
asked Apr 13, 2012 at 20:21
4
  • 3
    possible duplicate of Node.js: Parse JSON object Commented Apr 13, 2012 at 20:26
  • If you visit localhost:3000/employees.json in your browser, do you get JSON in your browser or do you get an error? Commented Apr 13, 2012 at 21:24
  • You've got some syntax error on line 19 of employees.js Commented Apr 13, 2012 at 21:46
  • Ryan, if I visit that in my browser I get JSON. Commented Apr 14, 2012 at 17:07

1 Answer 1

0

See this question:

Using Node.JS, how do I read a JSON object into (server) memory?

You should read the file first and then parse it.

var employees = JSON.parse(fs.readFileSync('employees.json', 'utf8'));

If for some reason your Rails app runs on some other machine, you need to make a http request for that. You could try this:

var site = http.createClient(port, host);
var request = site.request("GET", pathname, {'host' : host});
request.end();
request.on('response', function(response) {
 var json = '';
 response.on('data', function(chunk) {
 json += chunk;
 });
 response.on('end', function () {
 employees = JSON.parse(json);
 });
});
answered Apr 14, 2012 at 13:06
Sign up to request clarification or add additional context in comments.

2 Comments

Okay, here is what confused me. The ('employees.json', 'utf8') part...I don't have a JSON file, I have a JSON string that can be accessed here: localhost:3000/employees/1.json
ok that means you have to communicate with your rails app with a http request, like I mentioned in the second approach.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.