Backend 백엔드
[ 14 ] axios 로 api 전송 실습
박민우_
2024. 8. 7. 16:24
HTTP 405 에러 ( Method Not Allowed )
1. 잘못된 HTTP 메소드 사용
// 서버는 POST 메소드만 허용
app.post('/submit', (req, res) => {
res.send('Data submitted');
});
// 클라이언트가 GET 메소드로 요청
// GET /submit -> 405 Method Not Allowed
2. CORS ( Cross- Origin Resource Sharing ) 문제
3. url 잘못 작성
http:localhost:8080/tokens/phone // //생략으로 url 오류 발생
Front-End API 호출 코드
<!DOCTYPE html>
<html lang="ko">
<head>
<title>회원가입 연습하기</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
function zzz(){
// 1. 입력한 휴대폰 번호 가져오기
const myphone = document.getElementById('myphone').value
console.log("나의 핸드폰 번호 : " ,myphone)
// 2. 해당 휴대폰 번호로 인증번호 API 요청하기 (fetch , axios 등 사용 )
axios.post('http://localhost:8080/tokens/phone', {
phone : myphone
}).then((res)=>{
console.log(res.data)
document.getElementById('result').innerText = res.data
})
}
</script>
<body>
휴대폰번호: <input type="text" id="myphone"> <button onclick="zzz()">인증하기</button>
<div id="result">인증상태</div>
<button>회원가입하기</button>
</body>
</html>
Back-End 코드
라이브러리 설치
yarn add cors
cors 설정
import cors from 'cors'
app.use(cors())
전체 코드
import express from 'express' // 요즘 방식 => module
import {sendTokenToSMS ,checkPhone,getToken } from "./phone.js"
import cors from 'cors'
const app = express();
app.use(express.json()) // 옛날에는 bodyParser 사용
app.use(cors());
app.post('/tokens/phone',function(req,res){
const phone = req.body.phone;
console.log(phone)
// 휴대폰 자릿수 확인하기(10~11)
const isValid = checkPhone(phone);
if( !isValid) return res.status(400).send("휴대폰 번호가 유효하지 않습니다")
// 핸드폰 토큰 6자리 만들기
const token = getToken()
// 핸드폰번호에 토큰 전송하기
sendTokenToSMS(phone,token);
res.send("인증완료 !!")
})
app.listen(8080,()=>{
console.log('서버 시작')
});
728x90