@artman328
2018-05-15T08:28:21.000000Z
字数 2320
阅读 1073
node express web
mkdir weshopcd weshop
npm init
npm install --save express
//导入区const express = require('express')//建立应用程序对象const app = express()//使用中间件对请求对象进行审核、加工处理等//建立请求路由,将请求进行分发//开始监听请求app.listen(3000, function(){Sconsole.log("Server started on port 3000...")})
npm install -g nodemon
"scripts": {"start": "nodemon""test": "echo \"Error: no test specified\" && exit 1"},
以后可用 npm start 来启动应用并监视文件变动。
npm start
启动 web 应用服务(app.js),当看到以下输出时:
$ npm start> weshop@0.0.1 start D:\weshop> nodemon[nodemon] 1.17.4[nodemon] to restart at any time, enter `rs`[nodemon] watching: *.*[nodemon] starting `node app.js`Server started on port 3000...
说明已经成功启动。
http://localhost:3000/,网页显示:
Cannot GET /
原因是,我们还没有处理任何请求。
//建立请求路由,将请求进行分发app.get("/", function(req,res){res.send("您正在访问: " + req.path)})app.get("*", function(req,res){res.send("404, 请求的资源不存在!");})
http://localhost:3000/,但访问除此之处的路径,如:http://localhost:3000/abc,都将得到 404 响应。将 app.js 做如下改变:
//导入区...const path = require('path')...//使用中间件对请求对象进行导引、审核、加工处理等/*** 第一个参数表示虚拟路径 (随意起名) ,第二个参数由 express 指定* 静态文件的位置*/app.use('/static',express.static(path.join(__dirname,"public")))
在项目文件夹内建立 public 文件夹,在其中建立一个文本文件,比如 readme.txt,然后通过:
http://localhost:3000/static/readme.txt
进行访问,如果能够显示文件内容,说明静态文件访问配置正确。
//送出登录表单app.get("/login",function(){})//处理登录提交(请求包含用户名和密码)app.post("/login",function(){})
在项目文件夹中建立 controller 在文件夹,在其中创建一个 auth.js 文件,内容如下:
function send_login_form(req,res){res.send("send_login_form")}function do_login(req,res){res.send("do_login")}/*** 在 ES6 中:* {send_login_form,do_login}* 相当于* {send_login_form:send_login_form,do_login:do_login}*/exports = module.exports = {send_login_form,do_login}
//导入区...const auth_controller = require('./controller/auth');...//送出登录表单app.get("/login",auth_controller.send_login_form)//处理登录请求(请求包含用户名和密码)app.post("/login",auth_controller.do_login)
可用浏览器地址栏测试 get
http://localhost:3000/login
如果看到 send_login_form,说明路由正确。
可用 postman 测试 post
http://localhost:3000/login
如果看到 do_login,说明路由正确。
在 postman 中,post 表单数据:
username: admin
password adminpass
然后在控制器中试图获取这些参数。
首先:
安装 body-parser (请求体解析中间件)
npm install --save body-parser
