Nodejs Express4.x开发框架随手笔记

2020-06-18 05:56:26易采站长站整理

让我们来看看效果: http://localhost:3000/login 输入错误的和密码, 用户名:dad,密码:da

boostrap-nodejs

9. 页面访问控制

网站登陆部分按照我们的求已经完成了,但网站并不安全。

localhost:3000/home,页面本来是登陆以后才访问的,现在我们不要登陆,直接在浏览器输入也可访问。

页面报错了,提示<%= user.username %> 变量出错。

GET /home?user==a 500 15ms
TypeError: D:workspaceprojectnodejs-demoviewshome.html:2
1| <% include header.html %>
>> 2| <h1>Welcome <%= user.username %>, 欢迎登陆!!</h1>
3| <a claa=”btn” href=”http://www.geedoo.info/logout”>退出</a>
4| <% include header.html %>
Cannot read property ‘username’ of null
at eval (eval at <anonymous> (D:workspaceprojectnodejs-demonode_modulesejslibejs.js:
at eval (eval at <anonymous> (D:workspaceprojectnodejs-demonode_modulesejslibejs.js:
at D:workspaceprojectnodejs-demonode_modulesejslibejs.js:249:15
at Object.exports.render (D:workspaceprojectnodejs-demonode_modulesejslibejs.js:287:
at View.exports.renderFile [as engine] (D:workspaceprojectnodejs-demonode_modulesejsl
at View.render (D:workspaceprojectnodejs-demonode_modulesexpresslibview.js:75:8)
at Function.app.render (D:workspaceprojectnodejs-demonode_modulesexpresslibapplicati
at ServerResponse.res.render (D:workspaceprojectnodejs-demonode_modulesexpresslibres
at exports.home (D:workspaceprojectnodejs-demoroutesindex.js:36:8)
at callbacks (D:workspaceprojectnodejs-demonode_modulesexpresslibrouterindex.js:161

这个页面被打开发,因为没有user.username参数。我们避免这样的错误发生。

还记录路由部分里说的get,post,all的作用吗?我现在要回到路由配置中,再做点事情。

修改app.js文件

app.get(‘/’,routes.index);
app.route(‘/login’)
.all(notAuthentication)
.get(routes.login)
.post(routes.doLogin);
app.route(‘/logout’)
app.get(‘/’,routes.index);
app.route(‘/login’)
.all(notAuthentication)
.get(routes.login)
.post(routes.doLogin);
app.route(‘/logout’)
.get(authentication)
.get(routes.logout);
app.route(‘/home’)
.get(authentication)
.get(routes.home);

访问控制:

/ ,谁访问都行,没有任何控制
/login,用all拦截所有访问/login的请求,先调用authentication,用户登陆检查
/logout,用get拦截访问/login的请求,先调用notAuthentication,用户不登陆检查
/home,用get拦截访问/home的请求,先调用Authentication,用户登陆检查

相关文章 大家在看