Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express.js to GET json file in terminal

How do I GET a JSON file with express.js? I want to be able to access it in my Mac terminal. I'm working on a college assignment that asks me to write an HTTP server that will act as a simple data store. It must respond to GET, PUT, POST, and DELETE requests. I must use express.js instead of fs for this app.

So far, in my root directory I have a server.js file and I have a subdirectory called lib that holds another subdirectory called notes. Notes is where the JSON files will live.

In my root directory, I have a server.js file. This is all I have so far:

'use strict'
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var notes = './lib/notes';

app.use(bodyParser.json());

app.get('/', function(req, res) {
  //
  //this is the part I need help with
  //
}

var port = process.env.PORT || 3000;
app.listen(port, function() {
  console.log('Server started on port ' + port;
});

Once I have this GET request working, from my Mac terminal I should be able to send a GET request and receive all JSON files inside the notes directory.

like image 677
Farhad Ahmed Avatar asked Nov 18 '25 18:11

Farhad Ahmed


1 Answers

...from my Mac terminal I should be able to send a GET request and receive all JSON files inside the notes directory.

Provided you do not want to use fs module(well you dont need one either),

you can simply set a route for GET requests and send the json file in response with app.sendFile()

app.get('/',function(req,res){
    res.sendFile(path.normalize(__dirname + '/foo.json'))  
   //assuming your app.js and json file are at same level. 
   //You may change this to 'lib/notes/foo.json' to fit you case
})

path is a module that you would need to require().

__dirname is the directory that the currently executing script is in.

and finally foo.json is the file containing your json

{
    "name":"nalin",
    "origin":"stackoverflow"
}

Here's the complete code for app.js

var express = require('express');
var path = require('path');
var app  = express();


app.get('/',function(req,res){
    res.sendFile(path.normalize(__dirname + '/foo.json'))
})

app.listen(3000);

Which will help you run the node server with node app.js.

Finally you can access the json with by

  • visiting http://localhost:3000/ on your browser
  • by running curl command on your mac terminal curl localhost:3000

Hope this helps.

like image 96
nalinc Avatar answered Nov 20 '25 10:11

nalinc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!