[Node.js] express ์„ค์น˜ ๋ฐ app.js

express ์„ค์น˜

express๋ž€?

Node๋ฅผ ํ™œ์šฉํ•œ ์›น ํ”„๋ ˆ์ž„์›Œํฌ

express ์„ค์น˜

npm init // npm initial๋กœ ํ”„๋กœ์ ํŠธ ํŒŒ์ผ์„ ๋ชจ๋“ˆํ™”ํ•ด์ค€๋‹ค.
onpm install --save express
// --save => package.json์˜ dependencies ์— express ์ถ”๊ฐ€

app.js ์ž‘์„ฑ

app.js?

ํ†ต์ƒ์ ์œผ๋กœ express์—์„œ ์‹คํ–‰ํ•  ์—”ํŠธ๋ฆฌ ํŒŒ์ผ์„ app.js๋กœ ๋ช…๋ช…ํ•˜์—ฌ ๋งŒ๋“ ๋‹ค.

app.js

var express = require("express"); // express ๋ผ๋Š” ๋ชจ๋“ˆ์„ ๋กœ๋“œ
var app = express();
// express ๋ชจ๋“ˆ์ด application return, express์˜ ๊ทœ์น™์ž„(ํŠน์ • ์›๋ฆฌ x)

/* get method : router
routing(๊ธธ์„ ์ฐพ๋Š”๋‹ค.)ํ•œ๋‹ค๊ณ  ํ•จ => ์š”์ฒญ์ด ๋“ค์–ด์™”์„ ๋•Œ ์—ฐ๊ฒฐํ•ด์ฃผ๋Š” ์—ญํ• 
*/

app.get("/", function (req, res) {
  // get => ์‚ฌ์šฉ์ž๊ฐ€ ์›น์„œ๋ฒ„์— ์ ‘์†ํ•˜๋Š” ๋ฐฉ์‹ ์ค‘ ํ•˜๋‚˜(url์— ์น˜๊ณ  ์ ‘์†)
  res.send("Hello home page");
}); // home์œผ๋กœ ์ ‘์†ํ•˜๋ฉด function์ด ๋ณด๋‚ด๋Š” ์ธ์ž(request, response)๊ฐ€ ์‹คํ–‰
// request => ์š”์ฒญ์— ๋Œ€ํ•œ ๊ฐ์ฒด, response => ์‘๋‹ต์— ๋Œ€ํ•œ ๊ฐ์ฒด
app.get("/login", function (req, res) {
  // localhost:3000/login
  res.send("<h1>Login please</h1>"); // html ํƒœ๊ทธ ์‚ฌ์šฉ ๊ฐ€๋Šฅ!
});
app.listen(3000, function () {
  // 3000 => listening ํ•˜๋Š” ํฌํŠธ
  console.log("Connected 3000 port!");
  // listening์ด ์„ฑ๊ณตํ–ˆ์„ ๋•Œ ์‹คํ–‰๋˜๋Š” function
});

node app.js๋กœ ์‹คํ–‰ ํ›„

localhost:3000/ ๋ฐ
localhost:3000/login์œผ๋กœ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.