728x90
[Node.js 백엔드 기록] 2. Node.js 세팅, Express 설치, 기본 라우팅 (Localhost로)
[node.js 설치하기]
Node.js
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.
nodejs.org
디폴트 모드로 설정하기
[visual code 터미널에서 express 설치하기]
node.js 터미널 환경을 visual code에서 실행할 수 있도록 하자.
1. visual code에 작업 폴더 생성 후 디렉토리로 이동
2. express를 폴더 안에 생성하기
PS> npm install --save express
[app.js 파일을 생성해서 웹페이지 띄우기]
<app.js>
const express = require('express');
// express 모듈 가지고 옴, #include 같은 개념이다.
const app = express();
app.get('/home', function(req,res){ // app.get(path, 동작)
res.send('hello NodeJs');
res.send('this is my home');
})
app.get('/', function(req,res){ // app.get(path, 동작)
res.send('hello NodeJs');
res.send('this is default');
})
app.listen(3000, () => console.log('3000번 포트 대기'));
//app.listen 인자로 포트 번호가 들어온다.
<terminal>
PS> node app (서버실행코드)
PS> ctrl + c (서버다운)
get방식, post방식, put, delete 방식이 있다.
localhost : 자기 자신의 IP 주소이다.
localhost:3000/home : 3000은 포트 번호이다. 이때 path는 home
localhost:3000이면 path를 "/"라고 이해한다.
프로토콜 : IP주소 : 포트번호/path
http://localhost:3000/home
이때 path는 "/home"이다.
app.get (path, 동작) 동작에는 call back함수가 들어간다.
call back함수는 이름을 정의하지 않는다.
함수를 사용하는 이유 : 함수의 재사용을 위해서
동작을 하기 위한 함수는 한번만 쓰고 버려질 것이기 때문에 익명함수를 정의하기!
function(req,res){} parameter에 req,res 들어감
request는 사용자의 요청이 담긴다.
responds는 응답이 담긴다.
res에 send를 사용한다.
[번외 html 파일 띄우는 방법]
<main.html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>반가워요</title>
</head>
<body>
<div>환영합니다.</div>
</body>
</html>
728x90
'Back-End > Node.js' 카테고리의 다른 글
[Node.js 백엔드 기록] 4. method의 이해 & Path module (0) | 2023.07.20 |
---|---|
[Node.js 백엔드 기록] 3. html 이용해 form 데이터를 서버로 전달하기 (0) | 2023.07.19 |
[Node.js 백엔드 기록] 1. 웹서버 기본 지식 정리 (0) | 2023.03.26 |