Technology Stack

  • JavaScript
  • NodeJS
  • Express JS
  • Replit (for deployment)

Writing API

Initialize the project and install express

$ npm init -y
$ npm i express

Test Data

const products = [
    {
      name:'iPhone 13',
      color:'White',
      company:'Apple'
    },
    {
      name:'OnePlus 9',
      color:'Blue',
      company:'Oneplus'
    },
    {
      name:'iPhone 12',
      color:'Purple',
      company:'Apple'
    }
]

step:

  1. Import express into the project
const express = require('express');
  1. Initialize a variable to call the main express() method
const app = express();
  1. Set the port
const PORT = 8080;
  1. Use middleware to parse data into json
app.use(express.json());
  1. Add the data object to the file

  2. Complete code

const express = require('express');
const app = express();
const PORT = 8080;
app.use(express.json());

const products = [
    {
      name:'iPhone 13',
      color:'White',
      company:'Apple'
    },
    {
      name:'OnePlus 9',
      color:'Blue',
      company:'Oneplus'
    },
    {
      name:'iPhone 12',
      color:'Purple',
      company:'Apple'
    }
]
  1. Start the server and listen to the specified port
const express = require('express');
const app = express();
const PORT = 8080;
app.use(express.json());

const products = [
    {
      name:'iPhone 13',
      color:'White',
      company:'Apple'
    },
    {
      name:'OnePlus 9',
      color:'Blue',
      company:'Oneplus'
    },
    {
      name:'iPhone 12',
      color:'Purple',
      company:'Apple'
    }
]

app.listen(PORT, () => console.log(`API 🟢`))
  1. Create a method to handle GET requests
app.get('/products', (req, res) =>{
      res.status(200).send(products)
    })
Likes(0)

Comment list count 0 Comments

No Comments

WeChat Self-Service

WeChat Consult

TaoBao

support@elephdev.com

发表
评论
Go
Top