PHP nodejs ajax 연동

node js 2016. 8. 26. 22:02

//클라이언트

<!DOCTYPE html>

<html>

    <head>

        <script src="http://code.jquery.com/jquery-latest.js"></script>

    </head>

    <body>

        <div id="result"></div>

        <input type="text" id="msg" />

        <input type="button" value="get result" id="getResult" />

        <script>

            $('#getResult').click( function() {

                $('#result').html('');

                $.ajax({

                    url:'http://127.0.0.1:3000/test',

                    dataType:'json',

                    type:'POST',

                    data:{'msg':$('#msg').val(),

                     'name': 'lineage'},

                    success:function(result){

alert(result.name);

                $('#result').html(result.msg +"___"+ result.name);

                    }

                });

            })

        </script>

    </body>

</html>


//서버

router.post(['/test/:msg','/test'], function(req, res, next) {

    res.header("Access-Control-Allow-Origin" , "*")

    console.log('body: ' + JSON.stringify(req.body));

    res.send(req.body);

});


//서버 GET 방식

router.get('/test', function(req, res, next) {

    res.header("Access-Control-Allow-Origin" , "*")

    var str = '{ "name": "John Doe", "age": 42 }';

    var obj = JSON.parse(str);

    console.log(obj);

    res.send(obj);

});

블로그 이미지

칩사마코더

,