2 views

Data read from an array

prerequisite software

node, express, npm, yarn, or any code editor

Step 1: create a folder like node-api in desktop or any location in your computer

Step 2: open VS Editor > Terminal (keyboard command : Ctrl + ~)

then run yarn init . Create a package.json file

{
  "name": "node-api",
  "version": "1.0.0",
  "license": "MIT",
}

Step 3: create a index.js file into node-api folder

const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('I am from Node JS!!')
})

//server creation
app.listen(4000, () =>{
    console.log('server created and listening port 4000')
})

Step 4: install nodemon npm plugin for auto run server

update package.json file

{
  "name": "node-api",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "node index",
    "dev": "nodemon index"
  },
  "dependencies": {
    "express": "^4.17.1"
  }
}

More on request and response index.js

const express = require('express');
const app = express();

app.get('/', (req, res) => {
    console.log(req.url)
    res.send('I am from Node JS!!')
})
app.get('/hello', (req, res)=>{
    res.send('Hello bipon')
})
//server creation
app.listen(4000, () =>{
    console.log('server creted and listening port 4000')
})

As a response by object

app.get('/', (req, res) => {
    console.log(req.url)
    const author = {
        name: "bipon",
        profession: 'front end developer'
    }
    //JSON.stringify(author)
    res.send(author)
})

Variable path in Routing

app.get('/hello/:name', (req, res)=>{
    const name = req.params.name;
    res.send(`Hello ${name}`)
})

If don’t get any valid url then showing 404 Not Found

app.get('*', (req, res) => {
    res.send('404 Not Found')
})

Now data read from an array. so create a new array. Update bellow code.

let notes = [
    {
        id: 1,
        name: 'Note title 1',
        description: 'Note description 1'
    },
    {
        id: 2,
        name: 'Note title 2',
        description: 'Note description 2'
    },
    {
        id: 3,
        name: 'Note title 3',
        description: 'Note description 3'
    }
]
// get all notes
app.get('/notes', (req, res) => {
    if(notes.length == 0){
        return res.status(404).send('Note Not Found.')
    }else{
        res.send(notes)
    }
})
//get single note
app.get('/notes/:noteId', (req, res) => {
    const noteId = parseInt(req.params.noteId);
    const note = notes.find(note => note.id === noteId);
    if(note){
        res.send(note);
    }else{
        res.status(404).send('Note Not Found');
    }
})

Reference: status

Leave a Reply