Our Goals –
• Parsing Json Data in NodeJS App
Assumption
We already have a NodeJs project “myschool” in our working directory. If you don’t have the project then please create it. We have discussed it on our previous tutorial.
To do so –
1. Open comand prompt at our working directory and install “body-parser” by typing “npm install body-parser –save”.
2. And the out put will be like –
3. The “package.json” file will looks like
{ "name": "myschool", "version": "1.0.0", "description": "My First Project in NodeJS", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Tanmay Sarkar", "license": "ISC", "dependencies": { "body-parser": "^1.17.0", "express": "^4.15.0" } }
4. Open “app.js” file and paste the following code.
5. Now run this app using “node app” command at command prompt.
6. Now at command promt the output will be –
7. Open your browser and type http://localhost:5000/ and it will show the result as –
8. And if you check the console, the log will displayed as –
9. To terminate the server press “Ctrl+c”
Source Code :
var express = require('express'); var parser = require('body-parser'); var app = express(); var person ={ fname : 'Tanmay', lname : 'Sarkar', address : { add1 : 'my home address', add2 : 'my office address' } } app.get('/',function(req,res){ res.json(person); console.log('user accessing json parsing page'); }); app.listen(5000,function(){ console.log('server running on port 5000'); })
Thank you.