Express, Koa 및 Fastify를 사용하여 노드에 Rest API를 구축하는 방법 설명
평온 공약 요약
restful 약속은 우리에게 통일된 방식으로 CRUD (생성, 읽기, 업데이트, 삭제) 기능을 만드는 기본 경로를 제공하는 청사진을 제공합니다.
API Restful 라우팅
노선명
요청 방법
종점
결실
인덱스
얻다
/model
모든 항목 목록 되돌리기나타내다
얻다
/model/:id
일치하는 id가 있는 항목을 되돌려줍니다만들다
붙이다
/model
새 항목 만들기, 항목 반환 또는 확인업데이트
배치/패치
/model/:id
일치하는 ID가 있는 항목이 업데이트되었습니다.부수다
삭제
/model/:id
일치하는 ID가 있는 항목 삭제만약 우리가 API를 구축하지 않고 서버에 페이지를 보여준다면 두 개의 추가 경로가 있을 것이다.New 는 양식을 사용하여 페이지를 렌더링하여 새 객체를 작성하고 양식을 제출하면 작성 라우트를 트리거합니다.Edit, 기존 객체를 편집하기 위한 폼이 있는 페이지를 보여줍니다. 폼을 제출하면 업데이트 경로를 터치합니다.
우리가api를 구축하고 있기 때문에 편집과 새로 만드는 것은 불필요합니다. 정보를 수집하여 경로를 만들고 업데이트하는 데 제출하는 부담은 이api를 사용하는 프로그램을 구축하는 사람이 부담합니다.(프레임에 내장된 프런트엔드 어플리케이션)
우리가 어떤 데이터베이스를 사용하든, 어떤 유형의 데이터를 모델링하든, 이러한 약속은 바뀌지 않는다. 이것은 우리가 어떠한 언어, 프레임워크, 상하문에서 API를 구축하는 데 기초를 제공한다.
설치 프로그램
npm init -y
의 json 파일을 사용합니다. 이 파일은 본질적으로NodeJS에 프로젝트에 대한 정보 (의존항, 스크립트, 메타데이터 등) npm install express koa koa-router fastify
주의 사항
.gitignore
파일을 만들고 다음 내용을 추가하십시오./node_modules
npm install
npm uninstall <libraryname>
입니다. npmjs에서 라이브러리 디렉터리를 찾을 수 있습니다.com)우리 파일 만들기
폴더에 다음 파일 만들기
express-server.js
: 우리express 서버koa-server.js
: koa 서버를 실행하는 파일fastify-server.js
:fastify 서버를 실행하는 파일data.js
: 가상 데이터 파일Dummer 데이터 설정
데이터베이스와 관계 맵 (데이터베이스 테이블/집합을 클래스에 비추어 데이터베이스와 상호작용을 위한 라이브러리) 을 사용하는 것처럼 데이터 모델을 시뮬레이션하려면, 우리가 해야 할 일은...
data.js
// Class to Represent a Single Blog Post
class Post {
// Constructor function for creating new posts
constructor(title, body){
this.title = title
this.body = body
}
}
// Create an array to hold our posts
const posts = []
// Add a post to our posts array
posts.push(new Post("Title of Post", "Body of Post"))
// Export them to be used in other files
module.exports = {
Post,
posts
}
이 부분을 주의해라// Export them to be used in other files
module.exports = {
Post,
posts
}
노드의 다른 파일에서 사용할 수 있도록 변수를 공개하는 방법입니다.새 버전의 node에서 "type":"module"
패키지에 추가할 수 있습니다.json은 ES6 모듈 문법을 사용합니다. React와 Vue 등 전방 프레임워크에서 보았을 수도 있습니다.만약 네가 이렇게 한다면, 그것들은 이렇게 될 것이다.export Post
export posts
또는export default {
Post
posts
}
스크립트 설정
데드의 멋진 특징은 가방에서 스크립트를 정의할 수 있다는 것이다.json 파일.이것은 우리로 하여금 더 긴 명령을 더 짧게 할 수 있는 명령을 정의할 수 있게 한다.그러니까 싸.다음을 추가하십시오.
"scripts": {
"express": "node express-server.js",
"fastify": "node fastify-server.js",
"koa": "node koa-server.js"
},
이렇게 하면 다음 명령을 사용하여 다른 서버를 실행할 수 있습니다.npm run express
expressservernpm run fastify
fastify 서버 실행npm run koa
koa 서버 실행색인 경로
색인 루트의 목적은 특정 모델의 모든 항목을 되돌려 주는 것입니다. 우리의 예는 전체 게시물 그룹입니다.이 루트는 항상 '/모델' (우리의 예에서 '/posts') 에 대한 GET 요청으로 정의됩니다.모든 예시 다음에 해당하는 서버를 실행하고 브라우저에서localhost: 4000/posts로 이동합니다.
express-server.js
// Import Our Data
const {Post, posts} = require("./data")
// Import express
const express = require("express")
//create the express application
const app = express()
//The Index Route
app.get("/posts", (request, response) => {
// send the posts array as a json response
response.json(posts)
})
// Turn on the server
app.listen(4000, () => console.log("Server Listening on Port 4000"))
fastify-server.js
// Import Our Data
const {Post, posts} = require("./data")
// Import fastify
const fastify = require("fastify")
// Create application object
const app = fastify({logger: "true"})
// The Index Route
app.get("/posts", async (request, response) => {
// the response is the return value which is our posts array
return posts
})
// run server
app.listen(4000, () => console.log("listening on port 4000"))
koa-server.js
// Import Our Data
const {Post, posts} = require("./data")
// Import koa
const koa = require("koa")
// import koa router
const koaRouter = require("koa-router")
//create the koa application
const app = new koa()
// create a router for building routes
const router = koaRouter()
// Index Route
// context is a combo of the node request/response objects
router.get("/posts", async (context) => {
// The response is the value of the context body
context.body = posts
})
// Register routes
app.use(router.routes())
// Turn on the server
app.listen(4000, () => console.log("Server Listening on Port 4000"))
공연 노선
전시 노선은 단일 항목의 데이터를 얻는 것에 관한 것이다.이 항목은 url 매개 변수 (url의 가변 부분) 를 통해 확정됩니다.이것은 보통 데이터베이스 ID이지만, 우리는 하나의 그룹만 사용하기 때문에, 그룹 인덱스가 데이터베이스 ID를 대체할 것입니다. 디스플레이 루트는 보통 '/model/: ID' 에 대한 get 요청입니다.
경로의 ': id' 부분은 프레임워크에 'id' 라는 변수에서 URL이 저장된 부분을 볼 때 알려 줍니다.이것은 일반적으로 프레임 상하문이나 요청 대상 중'params'라는 대상에 저장됩니다.이것은 URL을 통해 정보를 노선으로 전달할 수 있도록 합니다.
매번 업데이트 후 서버를 실행하고 브라우저에서/posts/0으로 이동합니다!
express-server.js
// Import Our Data
const {Post, posts} = require("./data")
// Import express
const express = require("express")
//create the express application
const app = express()
//The Index Route
app.get("/posts", (request, response) => {
// send the posts array as a json response
response.json(posts)
})
// The Show Route
app.get("/posts/:id", (request, response) => {
// get the id from params
const id = request.params.id
// return json data
response.json(posts[id])
})
// Turn on the server
app.listen(4000, () => console.log("Server Listening on Port 4000"))
fastify-server.js
// Import Our Data
const {Post, posts} = require("./data")
// Import efastify
const fastify = require("fastify")
// Create application object
const app = fastify({logger: "true"})
// The Index Route
app.get("/posts", async (request, response) => {
// the response is the return value which is our posts array
return posts
})
// The Show Route
app.get("/posts/:id", async (request, response) => {
// get the id
const id = request.params.id
// return the item
return posts[id]
})
// run server
app.listen(4000, () => console.log("listening on port 4000"))
koa-server.js
// Import Our Data
const {Post, posts} = require("./data")
// Import koa
const koa = require("koa")
// import koa router
const koaRouter = require("koa-router")
//create the koa application
const app = new koa()
// create a router for building routes
const router = koaRouter()
// Index Route
// context is a combo of the node request/response objects
router.get("/posts", async (context) => {
// The response is the value of the context body
context.body = posts
})
// Show Route
router.get("/posts/:id", async (context) => {
// get the id
const id = context.params.id
// send the item as a response
context.body = posts[id]
})
// Register routes
app.use(router.routes())
// Turn on the server
app.listen(4000, () => console.log("Server Listening on Port 4000"))
노선 만들기
노선을 만들면 새로운 프로젝트를 만들 수 있습니다.Google은 요청체를 통해 데이터를 전달해서 새로운 프로젝트를 만듭니다. 따라서 Google은 get 요청이 아닌 get 요청을 보내기 위해postman이나 불면증 같은 도구가 필요합니다. (브라우저는 항상 get 요청을 보내는 것으로 기본값입니다.)
창설 루트는 보통 '/모델'의post 요청입니다. 예를 들어'/posts' 입니다.코드를 편집한 후,postman이나 Dominason을 사용하여localhost:4000/posts에post 요청을 보내고, 요청에 JSON 본문이 포함되어 있는지 확인하십시오.
{
"title":"title of a new post",
"body": "body of a new post"
}
express-server.js
*반드시 속도를 내야 한다.json () 중간부품, 그렇지 않으면 요청 본문을 읽을 수 없습니다// Import Our Data
const {Post, posts} = require("./data")
// Import express
const express = require("express")
//create the express application
const app = express()
// parse the body from json in request
app.use(express.json())
//The Index Route
app.get("/posts", (request, response) => {
// send the posts array as a json response
response.json(posts)
})
// The Show Route
app.get("/posts/:id", (request, response) => {
// get the id from params
const id = request.params.id
// return json data
response.json(posts[id])
})
// the Create Route
app.post("/posts", (request, response) => {
// create the new post, the data sent over is in the request body
post = new Post(request.body.title, request.body.body)
// push the new post in the posts array
posts.push(post)
// return the new post as json
response.json(post)
})
// Turn on the server
app.listen(4000, () => console.log("Server Listening on Port 4000"))
fastify-server.js
// Import Our Data
const {Post, posts} = require("./data")
// Import efastify
const fastify = require("fastify")
// Create application object
const app = fastify({logger: "true"})
// The Index Route
app.get("/posts", async (request, response) => {
// the response is the return value which is our posts array
return posts
})
// The Show Route
app.get("/posts/:id", async (request, response) => {
// get the id
const id = request.params.id
// return the item
return posts[id]
})
// the Create Route
app.post("/posts", async (request, response) => {
// create the new post, the data sent over is in the request body
post = new Post(request.body.title, request.body.body)
// push the new post in the posts array
posts.push(post)
// return the new post as json
return post
})
// run server
app.listen(4000, () => console.log("listening on port 4000"))
koa-server.js
npm install koa-bodyparser
를 설치하고 다음과 같이 가져오기// Import Our Data
const {Post, posts} = require("./data")
// Import koa
const koa = require("koa")
// import koa router
const koaRouter = require("koa-router")
// import koa bodyparser
const bodyParser = require("koa-bodyparser")
//create the koa application
const app = new koa()
// create a router for building routes
const router = koaRouter()
// Index Route
// context is a combo of the node request/response objects
router.get("/posts", async (context) => {
// The response is the value of the context body
context.body = posts
})
// Show Route
router.get("/posts/:id", async (context) => {
// get the id
const id = context.params.id
// send the item as a response
context.body = posts[id]
})
// the Create Route
router.post("/posts", async (context) => {
// get the body from context
const body = context.request.body
// create the new post, the data sent over is in the request body
post = new Post(body.title, body.body)
// push the new post in the posts array
posts.push(post)
// return the new post as json
context.body = post
})
// Register the bodyparser (must be before routes, or routes will run before body is parsed)
app.use(bodyParser())
// Register routes
app.use(router.routes())
// Turn on the server
app.listen(4000, () => console.log("Server Listening on Port 4000"))
노선을 갱신하다
업데이트 루트는put이나 patch 요청을 '/model/:id' 로 보내고 요청 본문의 데이터를 사용하여 지정한 id 업데이트 항목을 사용합니다.
코드를 업데이트한 후postman/posts를 사용하여 json의 본문이 있는'/posts/0'에put 요청을 보내서 기록을 업데이트합니다.
express-server.js
// Import Our Data
const {Post, posts} = require("./data")
// Import express
const express = require("express")
//create the express application
const app = express()
// parse the body from json in request
app.use(express.json())
//The Index Route
app.get("/posts", (request, response) => {
// send the posts array as a json response
response.json(posts)
})
// The Show Route
app.get("/posts/:id", (request, response) => {
// get the id from params
const id = request.params.id
// return json data
response.json(posts[id])
})
// the Create Route
app.post("/posts", (request, response) => {
// create the new post, the data sent over is in the request body
post = new Post(request.body.title, request.body.body)
// push the new post in the posts array
posts.push(post)
// return the new post as json
response.json(post)
})
// The Update Route
app.put("/posts/:id", (request, response) => {
// get the id from the url
const id = request.params.id
// get the request body
const body = request.body
// get the item to be updated
const post = posts[id]
// update the item
post.title = body.title
post.body = body.body
// return the updated item as a json response
response.json(post)
})
// Turn on the server
app.listen(4000, () => console.log("Server Listening on Port 4000"))
fastify-server.js
// Import Our Data
const {Post, posts} = require("./data")
// Import efastify
const fastify = require("fastify")
// Create application object
const app = fastify({logger: "true"})
// The Index Route
app.get("/posts", async (request, response) => {
// the response is the return value which is our posts array
return posts
})
// The Show Route
app.get("/posts/:id", async (request, response) => {
// get the id
const id = request.params.id
// return the item
return posts[id]
})
// the Create Route
app.post("/posts", async (request, response) => {
// create the new post, the data sent over is in the request body
post = new Post(request.body.title, request.body.body)
// push the new post in the posts array
posts.push(post)
// return the new post as json
return post
})
// The Update Route
app.put("/posts/:id", async (request, response) => {
// get the id from the url
const id = request.params.id
// get the request body
const body = request.body
// get the item to be updated
const post = posts[id]
// update the item
post.title = body.title
post.body = body.body
// return the updated item as a json response
return post
})
// run server
app.listen(4000, () => console.log("listening on port 4000"))
koa-server.js
// Import Our Data
const {Post, posts} = require("./data")
// Import koa
const koa = require("koa")
// import koa router
const koaRouter = require("koa-router")
// import koa bodyparser
const bodyParser = require("koa-bodyparser")
//create the koa application
const app = new koa()
// create a router for building routes
const router = koaRouter()
// Index Route
// context is a combo of the node request/response objects
router.get("/posts", async (context) => {
// The response is the value of the context body
context.body = posts
})
// Show Route
router.get("/posts/:id", async (context) => {
// get the id
const id = context.params.id
// send the item as a response
context.body = posts[id]
})
// the Create Route
router.post("/posts", async (context) => {
// get the body from context
const body = context.request.body
// create the new post, the data sent over is in the request body
post = new Post(body.title, body.body)
// push the new post in the posts array
posts.push(post)
// return the new post as json
context.body = post
})
// The Update Route
router.put("/posts/:id", async (context) => {
// get the id from the url
const id = context.params.id
// get the request body
const body = context.request.body
// get the item to be updated
const post = posts[id]
// update the item
post.title = body.title
post.body = body.body
// return the updated item as a json response
context.body = post
})
// Register the bodyparser (must be before routes, or routes will run before body is parsed)
app.use(bodyParser())
// Register routes
app.use(router.routes())
// Turn on the server
app.listen(4000, () => console.log("Server Listening on Port 4000"))
노선을 파괴하다
"/model/: id"에 대한 삭제 요청입니다. 이 요청은 지정한 id가 있는 항목을 삭제합니다. 코드를 업데이트한 후,postman/destory를 사용하여 "/posts/0"에 삭제 요청을 보내고, "/posts"에 get 요청을 보내서 삭제되었는지 확인하십시오.
express-server.js
// Import Our Data
const {Post, posts} = require("./data")
// Import express
const express = require("express")
//create the express application
const app = express()
// parse the body from json in request
app.use(express.json())
//The Index Route
app.get("/posts", (request, response) => {
// send the posts array as a json response
response.json(posts)
})
// The Show Route
app.get("/posts/:id", (request, response) => {
// get the id from params
const id = request.params.id
// return json data
response.json(posts[id])
})
// the Create Route
app.post("/posts", (request, response) => {
// create the new post, the data sent over is in the request body
post = new Post(request.body.title, request.body.body)
// push the new post in the posts array
posts.push(post)
// return the new post as json
response.json(post)
})
// The Update Route
app.put("/posts/:id", (request, response) => {
// get the id from the url
const id = request.params.id
// get the request body
const body = request.body
// get the item to be updated
const post = posts[id]
// update the item
post.title = body.title
post.body = body.body
// return the updated item as a json response
response.json(post)
})
// The Destroy Route
app.delete("/posts/:id", (request, response) => {
// get the id from the url
const id = request.params.id
// splice it from the array (remove it)
const post = posts.splice(id, 1)
// return the deleted post as json
response.json(post)
})
// Turn on the server
app.listen(4000, () => console.log("Server Listening on Port 4000"))
fastify-server.js
// Import Our Data
const {Post, posts} = require("./data")
// Import efastify
const fastify = require("fastify")
// Create application object
const app = fastify({logger: "true"})
// The Index Route
app.get("/posts", async (request, response) => {
// the response is the return value which is our posts array
return posts
})
// The Show Route
app.get("/posts/:id", async (request, response) => {
// get the id
const id = request.params.id
// return the item
return posts[id]
})
// the Create Route
app.post("/posts", async (request, response) => {
// create the new post, the data sent over is in the request body
post = new Post(request.body.title, request.body.body)
// push the new post in the posts array
posts.push(post)
// return the new post as json
return post
})
// The Update Route
app.put("/posts/:id", async (request, response) => {
// get the id from the url
const id = request.params.id
// get the request body
const body = request.body
// get the item to be updated
const post = posts[id]
// update the item
post.title = body.title
post.body = body.body
// return the updated item as a json response
return post
})
// The Destroy Route
app.delete("/posts/:id", async (request, response) => {
// get the id from the url
const id = request.params.id
// splice it from the array (remove it)
const post = posts.splice(id, 1)
// return the deleted post as json
return post
})
// run server
app.listen(4000, () => console.log("listening on port 4000"))
koa-server.js
// Import Our Data
const {Post, posts} = require("./data")
// Import koa
const koa = require("koa")
// import koa router
const koaRouter = require("koa-router")
// import koa bodyparser
const bodyParser = require("koa-bodyparser")
//create the koa application
const app = new koa()
// create a router for building routes
const router = koaRouter()
// Index Route
// context is a combo of the node request/response objects
router.get("/posts", async (context) => {
// The response is the value of the context body
context.body = posts
})
// Show Route
router.get("/posts/:id", async (context) => {
// get the id
const id = context.params.id
// send the item as a response
context.body = posts[id]
})
// the Create Route
router.post("/posts", async (context) => {
// get the body from context
const body = context.request.body
// create the new post, the data sent over is in the request body
post = new Post(body.title, body.body)
// push the new post in the posts array
posts.push(post)
// return the new post as json
context.body = post
})
// The Update Route
router.put("/posts/:id", async (context) => {
// get the id from the url
const id = context.params.id
// get the request body
const body = context.request.body
// get the item to be updated
const post = posts[id]
// update the item
post.title = body.title
post.body = body.body
// return the updated item as a json response
context.body = post
})
// The Destroy Route
router.delete("/posts/:id", async (context) => {
// get the id from the url
const id = context.params.id
// splice it from the array (remove it)
const post = posts.splice(id, 1)
// return the deleted post as json
context.body = post
})
// Register the bodyparser (must be before routes, or routes will run before body is parsed)
app.use(bodyParser())
// Register routes
app.use(router.routes())
// Turn on the server
app.listen(4000, () => console.log("Server Listening on Port 4000"))
결론
현재, 당신은 이미 세 개의 주요 NodeJS Micro 웹 프레임워크에 완전한crudapi를 만들었습니다!만약 다른 언어로 이 연습을 다시 시도하고 싶다면, 나는 이 강좌들을 추천한다.
Working with Python Masonite
- Creating an API with Rust and Rocket
Reference
이 문제에 관하여(Express, Koa 및 Fastify를 사용하여 노드에 Rest API를 구축하는 방법 설명), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/alexmercedcoder/intro-to-building-rest-api-in-node-with-express-koa-and-fastify-3c28텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)