实现基于Node.js的ajax前后端交互的简单例子

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Cyan1614/article/details/73386351

前端代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ajaxtest</title>
</head>

<body>
    <button onclick="ajax()">button</button>
</body>

<script src="jquery-1.9.1.js"></script>

<script>
    function ajax() {
        $.ajax({
            url: 'http://127.0.0.1:8080/',
            dataType: 'json',
            type: 'get',
            data: {
                test: 'ajax'
            },
            success: function (data) {
                console.log(data);
            }
        })
    };
</script>

</html>

后端代码:

var http = require('http');
var url = require('url');
var createServer = http.createServer(onRequest);

function onRequest(request, response) {
    response.writeHead(200, {
        'Content-Type': 'text/plain',
        'Access-Control-Allow-Origin': '*'
    });
    var str = JSON.stringify(url.parse(request.url, true).query);
    response.write(str);
    response.end();
}
createServer.listen(8080);
console.log('Server running  at http://127.0.0.1:8080/');


猜你喜欢

转载自blog.csdn.net/Cyan1614/article/details/73386351