๏ผsame origin ๊ธฐ์ค : ํ๋กํ ์ฝ(http/https), ๋๋ฉ์ธ(์ฃผ์), ํฌํธport ์ด ์ ์ด ๋ชจ๋ ๊ฐ์ ๊ฒ์ด same origin!
๏ผpromise์ผ ๋๋ง await๊ฐ ์๋ฏธ๊ฐ ์์, ํ์์๋ค๋ฉด ๊ตณ์ด ์ธ ์ด์ ๊ฐ ์๋ค.
express.js๋ node.js ํ๊ฒฝ์์ ์น์๋ฒ/API ์๋ฒ ์ ์์ ์ํด ์ฌ์ฉ๋๋ ํ๋ ์์ํฌ
res.end()
, res.send()
, res.json()
res.json({๊ฐ์ฒด}๋ค์ด๊ฐ)
res.send()
์์ ์ฐจ์ด: res.json()
์ ๋ฐ์ ์ธ์๋ฅผ json ๋ฌธ์์ด๋ก ๋ณํํด์ ํค๋์ 'Content-Type': 'application/json'์ผ๋ก ์
ํ
ํด์ฃผ๊ณ , body์ธ์์ ์ ์ฅํด์ ๋ด๋ถ์ ์ผ๋ก res.send
๋ฅผ ํธ์ถํด์ body์ธ์๋ก ๋๊ฒจ์คres.send()
res.jsonp([body])
๊ฐ ์์! app.use('/',routerFile๋ช
)
๋ฏธ๋ค์จ์ด
http์์ฒญ ์ธ์ํด์ ๋ก๋(?) ์ฐ๊ธฐ - cors ํค๋ ์ถ๊ฐ - ๋ฐ๋parse -> http ์๋ต ์ธ์๊น์ง - ์ปจ๋ฒ ์ด์ด ๋ฒจํธ์ ๊ฐ์ process์์ ์ด ์ค๊ฐ ๊ณผ์ ๋ค์ ๋ฏธ๋ค์จ์ด๋ก ์ฒ๋ฆฌ
- express์ ํฐ ์ฅ์
- get, use ๋ฑ
app.use(cors())
POST /
๋ฑ)์ ํฌํจ๋ body(payload)๋ฅผ ์ฝ๊ฒ ์ป๋ ๋ฐฉ๋ฒ, bodyParser ๋ฏธ๋ค์จ์ด ์ฌ์ฉ: app.use(express.json())
// ์์๋ฅผ ๋ค์๋ฉด
app.use((req, res, next) => {
console.log('๋ด๊ฐ ์ถ๊ฐํ ๊ณต์ ');
next(); // <- ํธ์ถ
});
โ๏ธ next๋ฅผ ํธ์ถํ์ง ์๋๋ค๋ฉด ํด๋ผ์ด์ธํธ์๊ฒ ์ด๋ค ์๋ต์ด๋ผ๋ ๋ณด๋ด์ผ ํจ
app.use((req, res, next) => { console.log(req.body) res.status(404).send('Not Found!'); // <- ์๋ต ์ฒ๋ฆฌ });
app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send({ // <- ์๋ต ์ฒ๋ฆฌ message: 'Internal Server Error', stacktrace: err.toString() }); });
req.params
vs req.qeury
req.params
๋ ๋ผ์ฐํ
({path})์ด user/:name์ ๊ฐ์ด {:id} ํํ์ธ ๊ฒฝ์ฐreq.query
๋ /flight?departur=ICN&destination=CJU ์ ๊ฐ์ ์ฟผ๋ฆฌ์คํธ๋ง์ด ๊ฐ์ฒด๋ก.