一、搭建node.js运行环境
Node.js安装
1.点击此处下载安装包
选择windows安装程序(.msi) 64位,

2.双击下载好的安装包,点击“运行”,

3.一路next到底,直到finish。


测试是否安装成功
按windows+R键,输入cmd运行,打开命令窗口,输入node -v回车,若下方出现v10.15.1即安装成功。10.15.1表示安装版本,注意:node后空格再-v。

二、nodejs之post数据解析
创建一个web服务器
1.新建一个文件夹nodejs-koa,新建一个index.js文件,添加如下代码:
const Koa = require('koa');
const router = require('koa-router')()
const app = new Koa();
app.use(router.routes());
app.listen(8088,function () {
console.log('启动成功')
});
2.测试端口号能否请求服务器,按住Shift建,在nodejs-koa文件夹中右键,选择在此处打开命令窗口;

3.输入node -v回车打开运行环境,接着输入node index.js回车,发现抛出异常,是因为我们没有引入Koa模块及其中间件,

4.在这里要引入koa模块和koa-bodyparser、koa-router中间件,输入npm i -s koa回车,会发现文件夹中新增了一个模块包以及一个json文件;


5.接着引入koa-bodyparser、koa-router中间件,分别输入npm i -s koa koa-bodyparser、npm i -s koa koa-router回车即可,
6.输入node index.js回车,发现该服务器启动成功,

7.在浏览器中输入localhost:8088,可访问且不报错;

添加表单,实现POST数据解析
1.在nodejs-koa文件夹中新建一个index.html文件,即表单,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<style>
.box{
margin: 10px auto 0 auto;
height: 300px;
width: 500px;
}
</style>
</head>
<body class="box">
<h1>nodejs-post数据解析</h1>
<form method="post" action="/">
<p>用户名</p>
<input name="userName"><br>
<p>密码</p>
<input name="password"><br>
<p>邮箱</p>
<input name="email"><br>
<button type="submit">submit</button>
</form>
</body>
</html>
2.完善index.js,用Koa发送get请求,并响应客户端返回解析数据。
const Koa = require('koa');
const router = require('koa-router')();
const body = require('koa-bodyparser');
const fs = require('fs');
const app = new Koa();
app.use(body());
router.get('/',async (ctx,next) => {
const data = fs.readFileSync('index.html','utf8');
ctx.body = data
});
router.post('/',async (ctx) => {
ctx.body = ctx.request.body
});
app.use(router.routes());
app.listen(8088,function () {
console.log('启动成功')
});
3.再次在命令窗口输入node index.js回车,显示启动成功。接着在浏览器中刷新localhost:8088,即可看到表单页面,并且提交后返回解析数据到页面中。


网友评论