Node.js 서버 실행하기 <express Library>

ouneno·2023년 7월 23일
0

Node.js

목록 보기
3/7
post-thumbnail

💻 server File 만들기

  • (참고) 해당 플젝은 express Library를 설치한 상태

프로젝트 폴더 내에 서버로 사용할 js파일을 만들어보자
명칭은? (서버이름명).js

❗️ (서버이름명).js

const express = require('express');
const app = express();
app.listen(8080, function(){
    console.log('listening on 8080')
});

설명

  • const express = require('express');
    express Library 설치했던 것을 참고할 때 사용

  • const app = express();
    app이라는 New instance를 생성

  • app.listen(8080, function() { });
    listen(포트번호, 서버 실행 후에 실행할 코드)


💻 Server run 서버실행

터미널에서 node를 사용해서 해당 js파일을 불러오기

❗️ node (서버이름명).js

node (서버이름명).js

💻 페이지 띄우기

⭐️ 저장 후 무조건 서버 재실행을 해야한다! ⭐️

어떤 고객이 main이라는 페이지에 방문을 하려고 한다.
localhost:8080/main 에 방문을 했을 경우 '어서오세요'라는 문구를 띄워보자

❗️.send('');

app.get('/main', function(req, res){
	res.send('어서오세요');
});

/main 이라는 페이지 방문시 res.send('어서오세요'); 라는 메서드에 의해 어서오세요 라는 문구를 볼 수 있게 된다.


💻 html 파일 가져와 띄우기

이전에는 응답메서드.send('blahblah') 를 사용해 실행했다면, 이번에는 /main페이지 방문시 html파일을 연결시켜보자.

우선 시작하기에 앞서 폴더 내에 index.html 파일을 생성할 것!

❗️ .sendFile(__dirname + '/');

app.get('/main', function(req, res){
	res.sendFile(__dirname + '/index.html');
});

💻 파일 참고

(서버파일명).js

index.html

profile
지속적인 성장을 추구하는 새싹 개발자입니다🌱

0개의 댓글