express_basic

BABY CAT·2022년 9월 30일
0

node.js

목록 보기
13/18
express :
	node.js 의 웹 프레임워크
    express속 많은 모듈 존재

1. 익스프레스 기본틀

ㄱ. 익스프레스 모듈 선언

익스프레스모듈 선언
const express = require("express");
const app = express();

ㄴ. app.get

app.get("/",(req,res)=>{ //홈하면주소
   res.send("<h1>Hello World</h1>"); //마지막에필수로주는것
});

ㄷ. app.listen

앱겟은 없어도 가능, Cannot GET /1 라고 뜨는 것을 path not found 로 바꿔주는 것
app.get("*", (req,res)=>{ // *는 지정경로가 아닌 모든 경로
	res.status(404).send("path not found"); 
}); // 지정경로가 아닌 주소를 입력하면 path not found를 출력한다
app.listen(3000, (req,res)=>{  //3000은포트 //리슨 기다리고 잇다가 오면 연결
    console.log("server is running at http://127.0.0.1:3000");
});

A. ㄱㄴㄷ 모아놓기

//익스프레스모듈
const express = require("express"); //express 프레임워크 선언 익스프레스속에 모듈 많음
const app = express();

// use-익스프레스가뭔가를사용하겟다 middleware 사용할떄많이사용
// http method - get, post, put, delete, all
// listen - 대기타는것  서버읽기

app.get("/",(req,res)=>{
   res.send("<h1>Hello World</h1>");
});

// routing path 별 처리해주는 함수

//아래두개 appget applisten 필수
// status code 404 를 보내는 코드 404라는에러를찍어주는역할 f12 네트워크 스테이터스에 404
app.get("*", (req,res)=>{  //*는 위에서 지정한경로가 아닌 모든 경로 즉 맨뒤에리슨바로위에붙는코드
  /*  res.status(404);
   res.send("path not found"); */
   res.status(404).send("path not found"); //위랑같은코드 메소드체이닝  페스낫파운드는 인터넷창에출력 -인터넷주소뒤에 / 이상한데 쳣을때상황
});

app.listen(3000, (req,res)=>{  //3000은포트 //리슨 기다리고 잇다가 오면 연결
   console.log("server is running at http://127.0.0.1:3000");
});

2. query.id vs params.id

ㄱ. query

http://localhost:3000/query?id=123
여기서 ? 부터는 쿼리 문법이라 id를 끌어올 땐 쿼리.아이디를 사용

// http://localhost:3000/query?id=123
app.get("/query", (req,res)=>{  //, (req,res) 이자린항상콜백함수가온다
    const id = req.query.id;  // ?id=123  필드명은 id 값은 123
    res.send(`<h1>/query: id - ${id}</h1>`);
}); 

ㄴ. params

http://localhost:3000/params/id/123
기본 호스트가 3000까지니까 겟을 params/id 까지하고 다음 값을 아이디로 받을려면
:id 후 파람스.id로 받는다
주소창이 어떻게 뜨는지 보고 params인지 query인지

app.get("/params/id/:id", (req,res)=>{  //, (req,res) 이자린항상콜백함수가온다
    const id = req.params.id;   
    res.send(`<h1>/params: id - ${id}</h1>`);
});
다중 파람스 받기
app.get("/set/:key/:value", (req,res)=>{
   const key = req.params.key;
   const value = req.params.value;
   res.set(key,value); //셋에의해 key:value묶임 f12 네트워크 헤더에
   res.send(`<h3>key=${key} value=${value}</h3>`)
})

0개의 댓글