Express - RESTApi - Basic CRUD

10327 단어 expressexpress

Setup

@echo off
set /p projectName="Enter project name: "

express %projectName% --view=pug
cd %projectName%

npm install
npm audit fix
npm i -g nodemon
npm start

pause

Add route for GET

index.js

var express = require('express');
var router = express.Router();

const courses = [
  { id: 1, name: "courses1" },
  { id: 2, name: "courses2" },
  { id: 3, name: "courses3" }
];

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});


router.get("/api/courses", (req, res) => {
  res.send([1, 2, 3]);
});

router.get("/api/posts/:year/:month", (req, res) => {
  res.send(req.params);
});

// 해당하는 ID를 찾아서 Respon
router.get("/api/courses/:id", (req, res) => {
  const course = courses.find(c => c.id === parseInt(req.params.id));
  if (!course) res.status(404).send(`ID was not found`);
  res.send(course);
});


module.exports = router;

Test GET

http://localhost:3000/api/posts/2011/

http://localhost:3000/api/courses/1

Add route for POST

router.post("/api/courses", (req, res) => {
  const course = {
    id: courses.length + 1,
    name: req.body.name
  };
  courses.push(course);
  res.send(course);
});

Test POST

http://localhost:3000/api/courses/12

좋은 웹페이지 즐겨찾기