본문 바로가기

기타/node js

node js ajax post 예제

728x90

ajax는 페이지의 일부만 로드하는 기술입니다.

오늘은 nodejs ajax를 사용하는 방법에 대해 알아보도록 하겠습니다.

 

1. html 코드 작성

아래와 같이 html 코드를 작성해 주세요.

<!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>
    <button class="ajax">ajaxbutton</button>
    <div class="result"></div>
    <script>
    //ajaxbutton을 눌렀을 때 실행되는 함수
        document.querySelector('.ajax').addEventListener('click', function () {
            var inputdata = 'han'
            sendAjax('http://localhost:3000/ajax', inputdata)
        })
		//send함수 'http://localhost:3000/ajax'주소에 inputdata를 보냅니다.
        function sendAjax(url, data) {

            var data = { 'name': data };
            data = JSON.stringify(data);
            
    		//data에 inputdata를 json형식으로 넣고 이를 xmlhttprequest를 통해 post방식으로 보냅니다.
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url);
            xhr.setRequestHeader('Content-type', "application/json");
            xhr.send(data);
			
            //서버에서 결과가 도착하면 그것을 result div에 입력합니다.
            xhr.addEventListener('load', function () {
                console.log(xhr.responseText);

                document.querySelector(".result").innerHTML = xhr.responseText
            });
        }

    </script>

</body>

</html>

 

 

2. 서버 코드

const express = require('express');
const app = express();

//post방식으로 데이터를 받을 때 필요한 모듈입니다.
//req에 데이터를 담아줍니다.
var bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))

//cors정책을 피하기 위한 모듈
const cors = require('cors')
app.use(cors());

//받은 데이터를 다음과 같이 가공해 json을 통해 클라이언트로 보내줍니다.
app.post('/ajax', function(req,res){
  var responseData = `hi ${req.body.name} i'm balmostory`
  res.json(responseData);
})

app.listen(3000, () => {
    console.log('listen t0 3000')
})

 

다음과 같은 결과가 나옵니다.

728x90

'기타 > node js' 카테고리의 다른 글

nodejs axios get, post예제  (0) 2021.01.29
[ Node js] nest js란?  (0) 2020.12.30
[Node js] express 서버 예제  (0) 2020.12.28
[Node js] request 모듈 사용법  (0) 2020.12.25
[Node js] chalk로 log colors 지정하기.  (0) 2020.12.23