GET 방식
- 변수를 받는 방법 : params, query
✓ params
http://localhost:3000/user/hyo
✓ query
http://localhost:3000/user/hyo?q=hyohyo&age=100
POST 방식
- params, body
- 주소창 요청 X
- Axios, Fetch 이용
const express = require('express')
const app = express()
const port = 3000
app.use(express.json())
app.post('/user/:id', (req, res) => {
const q = req.params
console.log(q);
const b = req.body
console.log(b);
res.send({'message' : 'test'})
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
CORS 이슈
- HTML 파일로 서버에 요청 했을 때, 보안상 이상한 곳에서 요청이 올 수 있기 때문에 막아버림
- HTML로 요청 할 때 CORS가 없으면 차단되는 경우 있음
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 12284 other projects in the npm registry using cors.
www.npmjs.com
CORS 설치
터미널 > npm install cors
const express = require('express')
const app = express()
const port = 3000
const cors = require('cors');
app.use(cors())
간단예제
http://localhost:3000/sound/cat
index.js
const express = require('express')
const app = express()
const port = 3000
const cors = require('cors');
app.use(cors())
app.get('/sound/:name', (req, res) => {
// const q = req.params
// q.name
const {name} = req.params
console.log(name)
if(name == 'dog') {
res.json({'sound' : '멍멍'})
} else if (name == 'cat') {
res.json({'sound' : '야용'})
} else if (name == 'pig') {
res.json({'sound' : '꿀꿀'})
} else {
res.json({'sound' : 'X'})
}
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch
Fetch 사용하기 - Web API | MDN
Fetch API는 HTTP 파이프라인을 구성하는 요청과 응답 등의 요소를 JavaScript에서 접근하고 조작할 수 있는 인터페이스를 제공합니다. Fetch API가 제공하는 전역 fetch() (en-US) 메서드로 네트워크의 리소
developer.mozilla.org
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>test</title>
</head>
<body>
<h1 id="sound"></h1>
<input id="name" type="text">
<button onclick="getSound()">API 요청</button>
<script>
function getSound() {
const name = document.getElementById('name').value
fetch(`http://localhost:3000/sound/${name}`)
.then((response) => response.json())
.then((data) => {
console.log(name)
console.log(data)
console.log(data.sound)
document.getElementById('sound').innerHTML = data.sound
});
}
</script>
</body>
</html>
실행
'Node.js' 카테고리의 다른 글
[Node.js] Express 설치, 실행 (0) | 2023.04.12 |
---|---|
[Node.js] 설치, 실행 (npm 사용 예시) (0) | 2023.04.12 |