--------------------------------------------开头-----------------------------------------------------
本篇文章关于node.js内容,只简述如何运用,而实际要使用node.js之前需要下载安装,并配置相关环境变量,本篇文章就不对该部分进行详细说明,可参考以下两个链接完成。
node.js下载官网:Node.js
node.js安装教程:Nodejs安装教程_彭佼的博客-CSDN博客_nodejs安装
本篇文章主要内容为,使用node.js创建后端服务,前端才用ajax访问后端http接口。本次示例使用设备操作系统为Windows 10家庭版。
-------------------------------------------------后端内容----------------------------------------------------
先看项目文件结构,如图1:
图1
图1项目文件结构说明:
node_moudle:为本次示例中所需要的node模块,其中包括如图2所示的内容,模块的作用请查看代码中的注释;
functionFile.js:为假设的外部js文件,因为在做实际项目中,一般情况下,不可能把所有的业务都写在同一个js文件中,而是有可能有其他的js文件,此篇代码顺便将调用外部js文件做为内容。
server.js:为node.js主服务启动文件,当然,文件名可以任意取,这个没关系。
图2
代码结构截图如图3:
图3
server.js文件代码如下:
var functionFile = require('./functionFile.js'); //调用外部js文件(测试)
var express = require("./node_moudle/express"); //该模块的作用是用于发布 post、get等相关http接口
const bodyParser = require("./node_moudle/body-parser"); //该模块的作用是对 http请求体 进行解析
var app = express();
//配置跨域相关
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
//监听8888端口
app.listen(8888, () => {
console.log("Nodejs Server is opend\n\n");
})
//http请求体 解析格式设置(可多样)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
//ServerFunc post接口
app.post("/ServerFunc", (req, res) => {
console.log("'ServerFunc' receipt of a request:");
console.log(req.body);
console.log("\n")
var retValue = "Hello" + " " + req.body.name + " " + "this is ServerFunc"
res.json({
"name": retValue
});
})
//FunctionFileFunc post接口
app.post("/FunctionFileFunc", (req, res) => {
console.log("'FunctionFileFunc' receipt of a request:");
console.log(req.body);
console.log("\n")
var functionFileRet = functionFile.SayHello(req.body.name); //调用外部js文件方法函数
res.json({
"name": functionFileRet
});
})
functionFile.js代码如下:
exports.SayHello = function(param) {
return "Hello" +" "+ param +" "+ "this is functionFile function";
}
在server文件夹(项目根目录)下按住键盘shift然后右键鼠标,启Windows PowerShell,如图4
图4
在命令行输入:node server.js,启动node.js服务,如图5
图5
至此,node.js的后端服务已经成功启动。
可使用Postman等相关http接口测试node.js发布的接口是否正常,因篇幅关系,本人自己也测试过代码,所以此处就不赘述Postman的相关内容,感兴趣可以搜索Postman等相关软件的使用。
直接进入前端部分。
---------------------------------------------前端内容------------------------------------------------
先看项目文件结构,如图6:
图6
图6项目文件结构说明:
.vscode文件夹:为vscode生成的文件夹,如果用别的编辑器(例如:HBuiderX之类的),就没有这个文件夹生成,影响不大,可不必理会;
js文件夹:文件夹里是相关js文件和jQuery,文件架构如图7,可参阅其说明;
index.html:为界面启动html文件;
图7
图7文件结构说明:
jquery文件夹:是相关jQuery文件,不清楚jQuery如何使用的是可以学一下,这里不赘述;
index.js文件:是此项目要调用后端接口的方法函数,详细可查阅代码。
index.html代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TestNodejs</title>
<!-- 引入jQuery -->
<script src="./js/jquery/dist/jquery.js" type="text/javascript" charset="utf-8"></script>
<!-- 引入index.js -->
<script src="./js/index.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<style type="text/css">
#serverRet {
width: 300px;
}
#FileRet {
width: 300px;
}
</style>
<input type="button" name="Test" value="UseServerFunction" onclick="ServerFunction()" />
<input type="text" name="serverRet" id="serverRet" />
<input type="button" name="Test" value="UseFunctionFileFunction" onclick="FunctionFileFunction()" />
<input type="text" name="FileRet" id="FileRet" />
</body>
</html>
index.js代码如下:
function ServerFunction() {
$.ajax({
type: "POST",
url: "http://localhost:8888/ServerFunc",
data: { "name": $("#serverRet").val() },
dataType: 'json',
success: function (data) {
$('#serverRet').val(data.name);
},
error: function (xhr) {
alert("error");
}
});
}
function FunctionFileFunction() {
$.ajax({
type: "POST",
url: "http://localhost:8888/FunctionFileFunc",
data: { "name": $("#FileRet").val() },
dataType: 'json',
success: function (data) {
$('#FileRet').val(data.name);
},
error: function (xhr) {
alert("error");
}
});
}
代码编写结束后,启动项目,如图8:
图8
任意在文本框中输入内容,如图9:
图9
点击界面按钮后,成功调取到接口的返回,如图10:
图10
接口调用图例,图11:
图11
--------------------------------------------结尾-----------------------------------------------------
至此,本篇文章相关代码等结束。
总结,使用node.js做为后端服务能很好的将前后端分离,因为node.js除了能发布http接口外,还能很方便的访问数据库(因为是测试程序,本篇不做介绍),对数据库进行增删改查等操作,且node.js能实现跨平台部署(在官网上有不同平台下的安装包 )。在实际项目中,可将node.js的后端服务部署在各类操作系统下,通过http接口调用,界面就能获取到想要的后台数据。
node.js的优点和缺点此文章就不做赘述,想了解的可以自行网上搜索。
感谢阅读,如有不足或错误,可评论区留言,共用讨论,谢谢!