leMS leMS - 4 months ago 15
JSON Question

Node GET request for json file not working

I'm using NodeJS to build a sample page just for some learning.
I'm trying to send a GET request to a file in the project's directory (using request module of node). The callback is just returning me an error and I can't figure out why this is happening.
Here's the code:

request.get(__dirname+"/public/app/test.json",function(err,data){
if(!err)
{
res.json(data);
console.log("Test Data Sent!");
}
else
{
res.send(err);
console.log("error occured! "+err);
}
});


The console log says this: "Error: Invalid URI e:/directory/nodejs/node-project/public/app/test.json"

Here's my directory structure: (Bold means folders)

E:

----directory

--------nodejs

------------node-project

------------server.js

------------package.json

----------------public

--------------------app

--------------------test.json

Can someone point out the problem?

Answer

A GET is a http request made to a web server. You can't GET a local file directly.

A local file can be read with fs.readFile.