웹/(Node.js)노드
(Node.js) node.js express로 서버구축하기
공부가싫다가도좋아
2021. 9. 7. 11:50
반응형
(Node.js) node.js express로 서버구축하기
* Node를 설치한 후 실행하셔야 됩니다.
1. 프로젝트파일 열기
프로젝트 폴더를 visual studio Code 혹은 다른 코드편집기에서 열어줍니다.
2. 터미널창에서 아래 명령어를 입력해 줍니다.(사진 참고하세요~)
> npm init
> npm install express --save
*npm init을 하고 계속 엔터를 쳐주시면 됩니다!!
(마지막 "Is this OK?"까지 엔터를 치고 폴더쪽 새로고침을 해주면, package.json파일이 생겨남)
3. 서버구축 코드
> 파일 생성 후 코드 입력.
파일명: server.js
const express = require("express");
const app = express();
/* localhost:3000/ 접속시 나올 메시지 */
app.get("/", (request, response) => {
response.send(`<h1>코드짜는 문과녀</h1>`);
});
/* localhost:3000/main 접속시 나올 메시지 */
app.get("/main", (request, response) => {
response.send(`
<h1>Hello World</h1>
<p>This is main page</p>
`);
});
/* localhost:3000/ 혹은 localhost:3000/main 외의
get하지 않은 페이지 접속시 나올 메시지. */
app.use((request, response) => {
response.send(`<h1>Sorry, page not found :(</h1>`);
});
/* 3000포트에서 서버 구동 */
app.listen(3000, () => {
console.log("localhost:3000 에서 서버가 시작됩니다.");
});
<결과 화면>
아래 명령어 입력 후 서버 실행
> node 파일명
http://localhost:3000/ 접속시 화면
http://localhost:3000/main 접속시 화면
"/" 와 "/main" 외의 주소로 접속시 화면
반응형