npm으로 express를 설치한 다음 해당 index.js에 코드를 작성한다.
const express = require("express");
const app = express()
app.use(() => {
console.log("WE GOT!")
}) // localhost:3000 페이지에서 요청을 하면 callback 실행
app.listen(3000, () => {
console.log("LISTEN!")
})
이후 localhost:3000 페이지에 접속하면 접속은 되지 않지만, 터미널로 요청은 들어온다.
const express = require("express");
const app = express()
app.use((req, res) => { // request, respond
console.log("WE GOT!")
res.send('<h1>This is my webpage</h1>') // HTTP 응답을 보내고 생성함
res.send({ color: "red" }) // json으로 콘텐츠 타입이 바뀜 ( 위 아래는 같이 못씀)
})
app.listen(3000, () => {
console.log("LISTEN!")
})
위처럼 app.use((req, res) => 으로 request와 respond 를 받는 콜백을 넣어 http에 응답을 보내는 res.send를 사용하면
클라이언트의 화면에 해당 글자가 나온다.
하지만 send 모든 요청에 응답해서 응답하면 그대로 끝이난다.
라우트는 응답된 코드를 가져와 응답을 갖는 어떤 코드와 맞춰주는 것을 뜻한다.
/cats => "mewo" /dogs => "woof" '/' 등등의 반응을 가진다.
app.get('/cats', (req, res) => {
console.log("Cat request!!");
}) // /cats과 일치하는 요청을 받을 때마다 시그니처 실행
http://localhost:3000/cats 라고 요청을 추면 Cat request!!가 터미널에 나온다.
app.get('/cats', (req, res) => {
res.send("MEOW!!")
}) // /cats과 일치하는 요청을 받을 때마다 시그니처 실행
app.get('/dogs', (req, res) => {
res.send("WOOF!")
})
app.get("/", (req, res) => {
res.send("this is homepage!!")
}) // cats이나 dogs가 없는 기본 홈페이지
app.post('/cats', (req, res) => {
res.send("this is post cat!")
}) // get이 아닌 post 로 보낸 요청
app.get('*', (req, res) => {
res.send("404ERROR!!")
}) // 위의 경로가 아닌 다른 경로를 요청하면 나오게 된다. 맨 위에 넣으면 다른 모든 요청을 덮어버리니 가장 마지막에 사용해야한다.
/cats이나 /dogs로 요청을 주면 respond send로 MEOW와 WOOF가 html로 화면에 나온다.
마지막의 app.post는 get이 아닌 post인 다른 요청을 주었다. 해당 요청을 post로 받으면 다른 res.send가 출력된다.
제네릭 터미널
app.get('/r/:subreddit', (req, res) => {
res.send("THIS IS A SUB");
})
요청을 /r/subreddit으로 보내면 res를 보낸다. /r/subreddit 뿐만이 아니라 : 를 사용했기 때문에,
/r/cats , /r/dogs 등을 보내도 동일하다. 즉 , subreddit이 뭐인지는 정하지 않았다.
app.get('/r/:subreddit', (req, res) => {
console.log(req.params);
res.send("THIS IS A SUB");
})
req.params ( params는 매게변수라는 뜻 ) 이후 /r/cats를 요청하면 터미널에 { subreddit: 'cats' } 가 출력된다.
이는 subreddit은 cats라는 문자열로 설정된 특성이라는 뜻이다.
app.get('/r/:subreddit', (req, res) => {
const { subreddit } = req.params; // subreddit 매게변수를 구조분해한다.
res.send(`This is ${subreddit}!!`);
})
이후 /r/cats 요청시 This is cats!! 나온다.
const obj = {
name: "John",
age: 18,
memo: "Hello",
};
const { name, age, memo } = obj;
console.log(name); // "John"
console.log(age); // 18
console.log(memo); // "Hello"
// 만약 구조 분해 할당을 사용하지 않는다면?
// 아래와 같이 직접 대입해 주어야 한다.
const name = obj.name;
const age = obj.age;
const memo = obj.memo;
위는 구조분해의 예시
제네릭 패턴을 이용하면 reddit과 같은 페이지를 만들 수 있다.
app.get('/r/:subreddit/comments/:postId', (req, res) => {
const { subreddit, postId } = req.params;
res.send(`This is ${subreddit} the id is ${postId}!!`);
})
/r/원하는 subreddit/comments/사용자 id
예를 들어 /r/cats/comments/asd91 을 요청하면 This is cats the id is asd91!! 이 출력된다.
쿼리 선택자 이용
쿼리를 이용하여서 요청을 할 수도 있다.
app.get('/search', (req, res) => {
const { q } = req.query;
res.send(`Search results for:${q}`);
})
여기서 쿼리란 https://www.google.com/search?q=slime ? 뒤의 q가 쿼리다.
즉, /search?q=dogs를 요청하면 Search results for:dogs 가 출력된다.
/search?q=dogs&color=red 를 입력하면 여러가지 키값을 받을 수 있다.
app.get('/search', (req, res) => {
const { q } = req.query;
if (!q) {
res.send("NOTHING FOUND!!!!")
}
res.send(`Search results for:${q}`);
})
응용해서 q가 아닐때를 if값으로 받으면 search로 쿼리를 아무것도 요청하지 않았을때에 출력할 html을 작성한다.
TIp
nodemon npm 을 설치하고
index파일을 nodemon으로 실행하면 서버파일을 바꿀때마다 재시작 할 필요가 없다
'The Web Developer 부트캠프 2022' 카테고리의 다른 글
NPM, Package.json (0) | 2022.09.29 |
---|---|
Node js 모듈과 NPM (0) | 2022.09.28 |
Node js 비동기화,동기화, FS 모듈 (0) | 2022.09.28 |
Node.js 기본 (0) | 2022.09.28 |
터미널 명령어 (0) | 2022.09.28 |