카테고리 없음

Nodejs express 패키지 모듈 설치 / 서버 띄우기(1)

Canyi 2022. 9. 28. 22:26
const { response } = require("express");
const express  = require("express");    //express 모듈 다운받기
const { request } = require("http");
const app = express();                 //app 변수에 express 실행


app.get("/",(request, response)=>{
    response.send("여기는 루트입니다.");     //localhost:3000에 반환값 보내기
});

app.get("/login", (request, response)=>{
    response.send("여기는 로그인 화면입니다.");    //localhost:3000/login  **/login 슬래시 꼭 넣기
});

app.listen(3000, function(){

    console.log("서버 가동");
});

위 코드를 그냥 실행하면  vscode 터미널에서 node apps.js 를 입력하면 아래와 같이 'cannot find module express' 라는 모듈을 찾지 못한다는 에러가 발생한다.

piaocanyi@bagchan-igdeMacBook-Pro login-lecture % node app.js
node:internal/modules/cjs/loader:959
  throw err;
  ^

Error: Cannot find module 'express'
Require stack:
- /Users/piaocanyi/Desktop/node/login-lecture/app.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:956:15)
    at Function.Module._load (node:internal/modules/cjs/loader:804:27)
    at Module.require (node:internal/modules/cjs/loader:1028:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/Users/piaocanyi/Desktop/node/login-lecture/app.js:1:18)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
    at Module.load (node:internal/modules/cjs/loader:1004:32)
    at Function.Module._load (node:internal/modules/cjs/loader:839:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/Users/piaocanyi/Desktop/node/login-lecture/app.js' ]
}
piaocanyi@bagchan-igdeMacBook-Pro login-lecture % npm install express

added 57 packages, and audited 58 packages in 1s

7 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
piaocanyi@bagchan-igdeMacBook-Pro login-lecture % npm install express --save

up to date, audited 58 packages in 447ms

7 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

해결법 

nps install express 입력해서 패키지 다운로드
패키지 추가완료
하지만 나는 npm install express --save라는 패키지로 다운로드 했음
packge-lock.josn이라는 폴더가 생성되고
node_modeles에 express라는 모듈이 추가됨
다시 node app.js 입력하면 서버 가동 이라는 텍스트가 출력, 이유는 페이지 맨 위의 코드로 확인
chrome에 localhost:3000 입력
출력결과
http://localhost:3000/login

localhost:3000으로 루트 페이지와 로그인 페이지 출력 완료! 마지막으로 서버 끄기!!

터미널에서 ctrl + c 입력

https://piaocanyi.tistory.com/172

 

Nodejs index.html 만들기 (1-2)

index.html이라는 파일을 만든다. !를 입력한다. <!DOCTYPE html> Document 이와 비슷한 코드가 나오지 않을 경우 마켓플레이스에서 HTML CSS Support 설치 const { response } = require("express"); const ex..

piaocanyi.tistory.com

apps.js & index.html 합치기