Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

wintertreey 님의 블로그

경로세팅, 라우팅, cors에러 본문

Node

경로세팅, 라우팅, cors에러

wintertreey 2024. 8. 11. 16:57

경로세팅하기

//환경변수 PORT가 존재하면 그 값을 사용하고, 아니면 3000사용하겠다는 의미.
app.set('port', process.env.PORT || 3000);

// 현재 폴더를 지정 : __dirname을 ECM(ECMAScript Module)환경에서 사용하기
const __filename = fileURLToPath(import.meta.url); //현재 실행중인 파일경로
const __dirname = path.dirname(__filename); //현재 실행 중인 폴더 경로

 

라우팅처리

app.get(요청, 라우칭처리)

app.get('/', function(req, res){
    res.send('아우넘졸리다 으악❄️❄️');
});

app.get('/java', function(req, res){
    res.send('<h2>Hello! Welcome to JAVA World!</h2>');
});

app.get('/node', function(req, res){
    res.send('<a href="https://naver.com">네이버</a>');
});

app.get('/abc', function(req, res){
    res.sendFile(path.join(__dirname, 'abc.html')); //현재 폴더의 abc.html호출
});

app.get('/json', (req, res) => {
    res.send({'이름':'홍길동'}); 
});

// 요청명?변수=값 인 경우 req.query로 받음.
// url 경로에 정보가 담긴경우 추출 http://localhost:3000/singer/bts/7
app.get('/user/:bun/:irum', (req, res) => {
    const {bun, irum} = req.params;

    res.json({bun, irum}); 
});
//http://localhost:3000/user/winter
app.get('/user/:season', (req, res) => {
    const {season} = req.params;

    if(season === 'summer'){
        res.json({'season':'더위'});
    }else if(season === 'winter'){
        res.json({'season':'추위'});
    }else{
        res.json({'season':'서늘'});
    }
});

app.get('/test',  (req, res) => {
    res.sendFile(path.join(__dirname, 'test.html')); //현재 폴더의 abc.html호출
});

 


cors

cors 문제 해결방법 : npm install cors 하고 
index.mjs에서 app.use(cors()) 하면 해결가. 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input id="name" type="text" placeholder="winter, summer 등 입력">
    <button onclick="getSeason()">api 요청</button>
    <script>
    function getSeason(){
        //동일 출처 정책에 의해 다른 도메인에서는 에러발생
        //Access to fetch at 'http://localhost:3000/user/winter' 


        const name = document.querySelector("#name").value;
        // http://localhost:3000/user 이 실제 전송되는 값 
        fetch(`http://localhost:3000/user/${name}`)
        .then((response) => response.json())
        .then((data) => {
            console.log(data);
        })
    }
    </script>
</body>
</html>

 

 

 

 

다른 도메인이기 때문에 

 

test.html파일을 이클립스 스프링 프로젝트에 넣어 스프링 서버로 띄웠다면 SOP정책위반으로 요청이 되지 않는다. 

 

해결방법

 

 

 

 

 

'Node' 카테고리의 다른 글

멤버 CRUD_ cors, json 파싱, 포트번호 설정. 라우팅  (0) 2024.08.13
회원 CRUD, splice()  (0) 2024.08.13
웹서버 모듈: http, figlet, express, nodemon  (1) 2024.08.11
이벤트, 예외처리  (0) 2024.08.11
동기 비동기  (0) 2024.08.11