Node.js / express

KHW·2021년 5월 24일
0

Node.js

목록 보기
2/19

express

Node.js를 위한 웹 프레임워크의 하나로,웹 애플리케이션, API 개발을 위해 설계되었다.

NodeJS를 사용하여 서버를 개발하고자 하는 개발자들을 위하여 서버를 쉽게 구성할 수 있게 만든 프레임워크

express를 안쓰고 Node.js로만 서버를 구성한다면?

HTTP 통신 방법도 배워야 하고, 패킷에 정보를 실어보내야 하니까, 패킷 구조도 배워야 하고 별 짓을 다해야한다.

express 설치방법

npm install express --save

간단한 기본코드

main.js

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

routing 하는방법

  1. pm2 및 express 설치
  2. main.js 코드 설정하기
  3. pm2 start main.js 명령어 실행

main.js

var fs = require('fs');
var template = require('./lib/template.js');
const express = require('express')
const app = express()
const port = 3000

app.get('/', (request, response) => {
  fs.readdir('./data', function(error, filelist){
    var title = 'Welcome';
    var description = 'Hello, Node.js';
    var list = template.list(filelist);
    var html = template.HTML(title, list,
      `<h2>${title}</h2>${description}`,
      `<a href="/create">create</a>`
    );
    response.send(html);
  });
})

app.get('/page/:pageId/:num',function(request,response){
 response.send(request.params)
})

중요한 점은 /:value1/:value2에 의해서 객체들이 정해진다는 것이다.

예를들어
아래와 같이 page에 그다음에 HTML을 넣은 곳은 pageId로써 HTML을 갖고 num으로써 1000을 갖는다.

출처

생활코딩

profile
나의 하루를 가능한 기억하고 즐기고 후회하지말자

0개의 댓글