개발세발
node, 프론트, 백 분리하기 본문
npm
$ npm init
* init : nitialize
{
"name": "node_jocoding",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
$ -g
내 컴퓨터 전체에 적용
; 전역으로 설치 시 충돌이 발생할 수도 있음
** figlet
: 아스키 아트 사용 가능
var figlet = require("figlet");
figlet("Hello World!!", function (err, data) {
if (err) {
console.log("Something went wrong...");
console.dir(err);
return;
}
console.log(data);
});
*Express
node.js 기반의 웹 프레임워크
https://www.npmjs.com/package/express
express
Fast, unopinionated, minimalist web framework. Latest version: 4.18.2, last published: 3 months ago. Start using express in your project by running `npm i express`. There are 66848 other projects in the npm registry using express.
www.npmjs.com
$ npm uninstall [module]
* uninstall 를 이용하여 사용하지 않는 모듈 삭제 가능
80
: http
443
: https (보안)
const express = require("express");
const app = express();
const port = 3000;
app.get("/", function (req, res) {
res.send("Hello World");
});
// app.listen(3000);
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
app.get('/', () => {} )
app.HTTP메소드 (라우팅, 콜백함수)
* HTTP 메소드
: 요청의 목적, 종류를 알려주기 위해 사용하는 수단
get | post |
주소창 o | 주소창 x |
app.get("/", function (req, res) {
res.send("Hello World");
});
app.get("/dog", function (req, res) {
res.send(`<h1>강아지</hi>`);
});
app.get("/cat", function (req, res) {
res.send("cat");
});
* send 안에 html 코드도 작성할 수 있음
axios | express |
요청을 보내는 것 | 요청에 대한 응답을 전달 |
➡️ aixos로 요청해서 express로 응답을 받음
*JSON
: Javascript Object Notation
*get 방식을 이용해 정보 받기
1. params
app.get("/user/:id", (req, res) => {
const q = req.params;
console.log(q);
res.json({'sound' : '멍멍'})
});
2.query
app.get("/user/:id", (req, res) => {
const q = req.query;
console.log(q);
});
* 실습
app.get("/sound/:name", (req, res) => {
// const q = req.params;
// 위의 내용을 아래와 같이 key 값만 적어주는 형식으로 줄여서 작성할 수 있음
const { name } = req.params;
if (name == "dog") {
res.json({ 'sound': "멍멍" });
} else if (name == "cat") {
res.json({ 'sound': "야옹" });
} else {
res.json({ 'sound': "알수없음" });
}
});
*CORS
: HTML의 요청을 응답이 잘 되도록 하는 것
- 교차 출처 리소스 공유, 교차 출처 자원 공유는 웹 페이지 상의 제한된 리소스를 최초 자원이 서비스된 도메인 밖의 다른 도메인으로부터 요청할 수 있게 허용하는 구조
https://www.npmjs.com/package/cors
cors
Node.js CORS middleware. Latest version: 2.8.5, last published: 4 years ago. Start using cors in your project by running `npm i cors`. There are 11598 other projects in the npm registry using cors.
www.npmjs.com
* 실습
: cors와 프론트엔드 연결해보기
<!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>Document</title>
</head>
<body>
<h1 id="sound"></h1>
<input type="text" id="name" />
<button onclick="getSound()">API 요청하기</button>
<script>
function getSound() {
const name = document.getElementById("name").value;
console.log(name);
fetch(`http://localhost:3000/sound/${name}`)
.then((response) => response.json())
.then((data) => {
console.log(data);
document.getElementById("sound").innerHTML = data.sound;
});
}
</script>
</body>
</html>
var express = require("express");
var cors = require("cors");
var app = express();
const port = 3000;
app.use(cors());
app.get("/sound/:name", (req, res) => {
// const q = req.params;
// 위의 내용을 아래와 같이 key 값만 적어주는 형식으로 줄여서 작성할 수 있음
const { name } = req.params;
if (name == "dog") {
res.json({ sound: "멍멍" });
} else if (name == "cat") {
res.json({ sound: "야옹" });
} else {
res.json({ sound: "알수없음" });
}
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
➡️ 굳이 html에 index.js를 연결해주지 않았는데도 서버가 켜진 상태에서는 알아서 url값을 활용하여 서버로 정보를 요청하고 값을 받아서 띄우는 과정이 가능했음
* sever를 내리면 값을 읽어오지 못함
'코딩공부 > Node' 카테고리의 다른 글
Node.js - 3️⃣ 템플릿 엔진 (0) | 2022.11.20 |
---|---|
Node.js - 2️⃣ 페이지 띄우기 (0) | 2022.11.20 |
Node.js - 1️⃣ 개념 (0) | 2022.11.18 |