$.ajax传输数据验证练习 和 服务端 运用node.js搭建本地服务器。

首先要下载nodejs

建立一个serve.js 放置后台的代码
建立一个index.html 放置前端的代码
然后就可以进行前端和后端的交互
记录纯属练习和理解

前端部分代码

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <script src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script>
    <style id="hello"></style>
    <style></style>
</head>

<body>
    <div>
        <div>手机号:
            <input type="text" id="phone">
        </div>
        <div>密&#8195;码:
            <input type="text" id="password">
        </div>
        <button id="btn">请点击</button>
        <div class="calltext">
        </div>
    </div>
</body>
<script type="text/javascript">
    $(document).ready(function() {

        $("#btn").click(function() {
            var phone = $("#phone").val();
            var password = $("#password").val();
            var data_val = {
                "phone": phone,
                "password": password
            };

            $.ajax({
                url: 'http://localhost:8083/hhh',
                dataType: "json", //jsonp是针对于get的跨域解决办法
                data: data_val,
                type: 'POST',
                success: function(data) {
                    console.log(data);
                    if (data.data) {
                        $('.calltext').html("登陆成功")
                    } else {
                        $('.calltext').html("登陆失败")
                    }
                },
                error: function(xhr, status, error) {
                    console.log('Error: ' + error.message);
                },
            });
        });
    });
</script>


</html>

后台部分代码

//引入express模块
const express = require('express');
const app = express();
//解析post请求过来的数据
var bodyParser = require('body-parser');


//解决跨域的问题
app.all('*', function(req, res, next) {
    //允许的来源
    res.header("Access-Control-Allow-Origin", "*");
    //允许的头部信息,如果自定义请求头,需要添加以下信息,允许列表可以根据需求添加
    res.header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild");
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    //允许的请求类型
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    next();
});


app.use(bodyParser.urlencoded({ extended: false }));
app.post('/hhh', (req, res) => {
    console.log(req.body)
    if (req.body.phone == "12345678" && req.body.password == "123123") {
        res.send({ "data": true })
    } else {
        res.send({ "data": false })
    }
});


app.listen(8083, () => {
    console.log('Server is running at http://localhost:8083')
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值