【NodeJS】最简单的不用路由及框架的前后台交互

声明:index.html 与 app.js位于同一级目录

POST 请求

post方式提交的数据,需要监听两个事件:

  • data —— 当请求发送数据会触发data事件
  • end —— 当数据接收完成会触发end事件。

index.html

<!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>Document</title>
</head>
<body>
    名字:
    <input type="text" name="name" id="name" placeholder="请输入用户名">
    <button type="button" onclick="send()">发送</button>
    <div id="returnVal"></div>

    <script>
        function send() {
            var name = document.getElementById('name').value;

            // 1.创建XMLHttpRequest对象
            var xhr = new XMLHttpRequest();
            // 2.请求行
            xhr.open('POST', 'http://127.0.0.1:3000');
            // 3.请求头
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            // 4.设置数据
            xhr.send(name);      
            // 5.监听服务器响应
            xhr.onreadystatechange = function(){
                if (xhr.readyState==4 && xhr.status==200){
                    document.getElementById('returnVal').innerHTML = xhr.responseText;
                }
            };
        };
    </script>
</body>
</html>

app.js

var http = require('http');

http.createServer(function (req, res) {
    var dataContent = '';
    req.on('data', function(data) {      // 接收客户端发送过来的数据
        dataContent += data;
    });

    req.on('end', function() {
        res.writeHeader(200, {
            'Content-Type': 'text/plain',
            'Access-Control-Allow-Origin': '*'   //解决跨域问题
        });
        res.write("hello:" + dataContent);
        res.end();
    })
}).listen(3000, function(){
    console.log("listen to: 3000");
});

将这两个文件放在xampp本地服务器里的htdocs中并开启Apache服务器
node app.js 启动node服务器

演示效果图:
这里写图片描述

GET 请求

app.js

var http = require('http');
var fs = require('fs');

var app = http.createServer(function(req, res){
    res.setHeader("Content-Type", "text/html; charset=utf-8");
    if(req.url === '/'){
        fs.readFile('./templates/index.html', 'utf-8', function(err, data){
            if(!err){
                res.write(data);
                res.end();
            }
        })
    }else if(req.url === '/login'){
        fs.readFile('./templates/login.html', 'utf-8', function(err, data){
            if(!err){
                res.write(data);
                res.end();
            }
        })
    }else if(req.url === '/register'){
        res.write("欢迎来到注册页面");
        res.end();
    }else if(req.url === '/admin'){
        res.write("欢迎来到后台管理页面");
        res.end();
    }else{
        res.write("404 你找的页面飞了");
        res.end();
    }
});

app.listen(3000, function(){
    console.log('app is listening at port 3000');
})

效果演示图:
这里写图片描述

拓展:【NodeJS】http.createServer与http.Server对比

猜你喜欢

转载自blog.csdn.net/u013451157/article/details/80462642
今日推荐