Home > Article > Web Front-end > Share Express + Node.js implementation of login interceptor detailed explanation
This article mainly introduces the example code for implementing the interceptor in Express + Node.js. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor to take a look.
Introduction
The interceptor here corresponds to the filter in spring MVC, all http The corresponding code/resource can only be accessed after the request is processed by the interceptor.
The most typical application scenario is to implement access permission control, giving different users/user groups different access permissions to pages and interfaces, and only allowing access to allowed pages and interfaces.
Scenario
app.post('/login', function(request, res, next){ // do something }); app.post('/getData',function(request, res, next){ // do something var data="some data"; res.send({"data":data}); });
If no processing is done, anyone who sends a getData post request can read it directly from the background Fetching data does not require any login, you only need to know the interface.
Corresponds to each interface. If permission judgment is added under each interface, the code will be very repetitive, so the aspect-oriented approach comes. You can add the interceptor before each http request. , to realize the function of permission judgment.
Implementation
// 所有用户可以访问index.html, error.html // admin可以访问admin.html, /getData // 登陆用户可以访问home.html app.all('/*', function(request, res, next){ // 思路: // 得到请求的url // 然后得到request的cookie,根据cookie得到当前登陆的用户 // 判断用户对应url的权限 var jsPattern=/\.js$/; var url=request.orignalUrl; if(jsPattern.test(url)){ // 公共部分,放行 next(); return; } if(url=='index.html'||url=='error.html'){ next(); return; } var cookie=JSON.stringify(req.cookies); if(access){ next(); } else{ res.redirect('error.html'); } });
Implementation ideas:
1. Intercept all requests ( The above is enough), get the currently accessed url
2. Get the current user based on the cookie
3. Determine whether it is possible based on the identity of the url and the user. Access
4. If you can call next();
5. If you cannot access, return error message
Note
The above is the detailed content of Share Express + Node.js implementation of login interceptor detailed explanation. For more information, please follow other related articles on the PHP Chinese website!