首先要下载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>密 码:
<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')
})