반응형

 

개발환경 : Windows10, VScode, Node.js(ver 15.12.0)

 

 

1. server.js 파일 생성한다.

 

<server.js 코드>

// 서버 사용을 위해 http모듈을 http라는 변수에 담는다.
var http = require('http');

// http모듈로 서버를 생성한다. 
var app = http.createServer(function(req,res){
  // 사용자에게 요청이 들어오면 응답해준다.
  // 콘텐츠타입은 텍스트, html형식!
  res.writeHead(200,{'Content-Type':'text/html'});
  res.end('welcome!!');
});

// listen 함수로 3000 포트에 서버를 실행한다.
app.listen(3000, function(){
  console.log("server is running.")
});

 

 

2. 터미널에 "node server.js" 를 입력하여 서버생성

 

 

3. 설정한 포트번호로 접속하여 서버생성 및 응답 확인

"localhost:포트번호"로 접속하시면 됩니다.

 

 

 

 

<Node.js로 서버생성 후 해당 서버에 html파일 로드하기>

 

<main.html>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>https://cocoon1787.tistory.com/</title>
  </head>
  <body>
    <div>환영합니다.</div>
  </body>
</html>

 

<server.js>

// 서버 사용을 위해 http모듈을 http라는 변수에 담는다.
var http = require('http');
var fs = require('fs');

// http모듈로 서버를 생성한다. 
var app = http.createServer(function(req,res){
  var url = req.url;
    if(req.url == '/'){
      url = '/main.html';
    }
    if(req.url == '/favicon.ico'){
      return res.writeHead(404);
    }
    res.writeHead(200);
    res.end(fs.readFileSync(__dirname + url));
 
});

// listen 함수로 3000 포트에 서버를 실행한다.
app.listen(3000, function(){
  console.log("server is running.")
});

 

 

 

 

<express 프레임워크를 사용시 코드>

 

<main.html>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>https://cocoon1787.tistory.com/</title>
  </head>
  <body>
    <div>환영합니다.</div>
  </body>
</html>

 

<server.js>

var express = require('express')
var app = express()

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

app.listen(3000);

 

 

 

 

현재 노드js 공부중이며 확실히 express프레임워크를 사용하는것이 편하긴 하다,,,,

 

반응형

+ Recent posts