ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Nodejs] Express 시작하기
    Nodejs 2023. 8. 10. 20:44

     

    프로젝트에 사용할 Express를 시작해보려고합니다. 우선 Express를 설치합니다

    npm i express

    설치가 완료되었으면 expressjs를 작성해보겠습니다

    우선 모듈을 불러올때 require대신 import를 쓰기위해서 CommonJS방식에서 ES Module방식을 사용해주기 위해

    package.json에서 추가를 해주겠습니다

    {
      "name": "12_study-matching-service",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "repository": {
        "type": "git",
        "url": "git+https://github.com/dpqls0356/study-matching-service.git"
      },
      "author": "",
      "license": "ISC",
      "bugs": {
        "url": "https://github.com/dpqls0356/study-matching-service/issues"
      },
      "homepage": "https://github.com/dpqls0356/study-matching-service#readme",
      
      "dependencies": {
        "express": "^4.18.2"
      }
    }

    현재 저의 package.json입니다. 여기에 한줄을 추가해주겠습니다

    "type" : "module"

    을 추가해주면 ES Moudle방식으로 require 대신 import문을 사용할 수 있게 됩니다.

    {
      "type": "module", //이 줄 추가
      "name": "12_study-matching-service",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "repository": {
        "type": "git",
        "url": "git+https://github.com/dpqls0356/study-matching-service.git"
      },
      "author": "",
      "license": "ISC",
      "bugs": {
        "url": "https://github.com/dpqls0356/study-matching-service/issues"
      },
      "homepage": "https://github.com/dpqls0356/study-matching-service#readme",
      "dependencies": {
        "express": "^4.18.2"
      }
    }

    server.js파일을 만들어 작성하겠습니다.

     

    import문을 사용해 express모듈을 현재 파일로 가져오고 가져온 express모듈로 Express 애플리케이션을 생성해줍니다

    //server.js
    import express from "express";
    
    const app = express(); //express.js 애플리케이션 생성

    포트 번호는 8080번으로 설정해주겠습니다.

    import express from "express";
    
    const app = express();
    const PORT = 8080; // 포트번호 8080
    app.use(express.json()); // JSON데이터 파싱

    이 후 JSON형식의 데이터를 파싱해 JS객체로 변환 해주기 위해 아래와 같은 코드를 추가해줍니다

    app.use(express.json()); // JSON데이터 파싱

    CORS문제와 클라이언트에서 서버로의 API요청을 허용하기 위해 CORS미들웨어를 사용해주겠습니다. 우선 cors패키지를 설치해 줍니다

    npm i cors

    이 후 cors를 import 해주고 아래와 같이 작성해줍니다

     

    import express from "express";
    import cors from "cors"; //import 하기
    
    const app = express();
    const PORT = 8080;
    
    app.use(express.json());
    app.use(cors()); //CORS 미들웨어 등록

    마지막으로 서버가 시작되고 리스닝을 시작할때 실행할 함수를 정의 하고 서버가 리스닝을 시작하는 부분을 작성하겠습니다.

    const handleServer = () => {
      console.log(`Server listening on port http://localhost:${PORT}`);
    };
    
    app.listen(PORT, handleServer);

    최종 코드입니다.

    import express from "express";
    import cors from "cors";
    
    const app = express();
    const PORT = 8080;
    
    app.use(express.json());
    app.use(cors());
    
    const handleServer = () => {
      console.log(`Server listening on port http://localhost:${PORT}`);
    };
    
    app.listen(PORT, handleServer);

    이제 서버를 실행해 보겠습니다.

    npm start

    실행 해보면

    이렇게 뜨면서 정상적으로 서버가 실행되고 있는것을 볼 수 있습니다. 

     

Designed by Tistory.