Express - RESTApi - Basic CRUD
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
Author And Source
이 문제에 관하여(Express - RESTApi - Basic CRUD), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@csk917work/Express-RESTApi-Demo저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)