javascript - express.js to GET json file in terminal -


how json file express.js? want able access in mac terminal. i'm working on college assignment asks me write http server act simple data store. must respond get, put, post, , delete requests. must use express.js instead of fs app.

so far, in root directory have server.js file , have subdirectory called lib holds subdirectory called notes. notes json files live.

in root directory, have server.js file. have 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 part need   // }  var port = process.env.port || 3000; app.listen(port, function() {   console.log('server started on port ' + port; }); 

once have request working, mac terminal should able send request , receive json files inside notes directory.

...from mac terminal should able send request , receive json files inside notes directory.

provided not want use fs module(well dont need 1 either),

you can set route requests , send json file in response app.sendfile()

app.get('/',function(req,res){     res.sendfile(path.normalize(__dirname + '/foo.json'))      //assuming app.js , json file @ same level.     //you may change 'lib/notes/foo.json' fit case }) 

path module need require().

__dirname directory executing script in.

and foo.json file containing json

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

here's complete code 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 run node server node app.js.

finally can access json

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

hope helps.


Comments