๐ ๊ณต๋ถํ๋ ์ง์ง์ํ์นด๋ ์ฒ์์ด์ง?
[Express ์น ์๋ฒ ๋ง๋ค๊ธฐ] (1) express ๋ชจ๋๋ก ์๋ฒ ๊ตฌ์ถํ๊ธฐ ๋ณธ๋ฌธ
๐ฉ๐ป ๋ฐฑ์๋(Back-End)/Node js
[Express ์น ์๋ฒ ๋ง๋ค๊ธฐ] (1) express ๋ชจ๋๋ก ์๋ฒ ๊ตฌ์ถํ๊ธฐ
์ง์ง์ํ์นด 2023. 4. 23. 23:28728x90
๋ฐ์ํ
<๋ณธ ๋ธ๋ก๊ทธ๋ Node.js ๊ต๊ณผ์๋ฅผ ์ฐธ๊ณ ํด์ ๊ณต๋ถํ๋ฉฐ ์์ฑํ์์ต๋๋ค :-)>
๐ express ๋ชจ๋๋ก ์๋ฒ ๊ตฌ์ถํ๊ธฐ
๐ app.js
// express : http ๋ชจ๋ ๋ด์ฅ๋์ด์ ์๋ฒ์ ์ญํ
const express = require("express");
const app = express();
require("dotenv").config();
// ์๋ฒ๊ฐ ์คํ๋ ํฌํธ
// app.set("ํค, ๊ฐ") : ๋ฐ์ดํฐ ์ ์ฅ
app.set("port", process.env.PORT || 3000);
// app.get("์ฃผ์, ๋ผ์ฐํฐ") : ์ฃผ์์ ๋ํ GET ์์ฒญ์ด ์ฌ ๋ ์ด๋ค ๋์ ํ ์ง ์ ๊ธฐ
app.get("/", (req, res) => {
res.send("Hello express");
});
// HTTP ์น ์๋ฒ์ ๋์ผ
app.listen(app.get("port"), () => {
console.log(app.get("port"), "๋น ํฌํธ์์ ๋๊ธฐ์ค");
});
๐ HTML ๋ก ์๋ตํ๊ธฐ
๐ app.js
// express : http ๋ชจ๋ ๋ด์ฅ๋์ด์ ์๋ฒ์ ์ญํ
const express = require("express");
const app = express();
// ํ์ผ ๊ฒฝ๋ก
const path = require("path");
require("dotenv").config();
// ์๋ฒ๊ฐ ์คํ๋ ํฌํธ
// app.set("ํค, ๊ฐ") : ๋ฐ์ดํฐ ์ ์ฅ
app.set("port", process.env.PORT || 3000);
// app.get("์ฃผ์, ๋ผ์ฐํฐ") : ์ฃผ์์ ๋ํ GET ์์ฒญ์ด ์ฌ ๋ ์ด๋ค ๋์ ํ ์ง ์ ๊ธฐ
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "/index.html"));
});
// HTTP ์น ์๋ฒ์ ๋์ผ
app.listen(app.get("port"), () => {
console.log(app.get("port"), "๋น ํฌํธ์์ ๋๊ธฐ์ค");
});
๐ index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Express Server</title>
</head>
<body>
<h1>Express</h1>
<p>๋ฐฐ์๋ณด์!</p>
</body>
</html>
728x90
๋ฐ์ํ
'๐ฉโ๐ป ๋ฐฑ์๋(Back-End) > Node js' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Comments