使用中间件使用ExpressJS调用身份validationAPI
我正在使用两个Node.js + Express应用程序:
- 后端
- authentication
而我的前端是build立在AngularJS上的
基本上我试图发送一个JSON Web令牌与后端的每个请求,然后使用路由中间件来调用身份validationAPI。 它validation该令牌并将用户数据添加到请求。 最后,我使用用户数据在后端处理请求以获取我的资源。
var app = angular.module('myApp', [<dependencies> ]).config(function ($routeProvider, $locationProvider, $httpProvider) { $routeProvider .when('/', { templateUrl: 'views/login.html' }) .when('/foo', { templateUrl: 'views/foo.html' }) .otherwise({ templateUrl: '404.html' }); $locationProvider.html5Mode({ enabled: false, requireBase: false }); $httpProvider.interceptors.push(['$q', '$location', '$sessionStorage', function($q, $location, $sessionStorage) { return { 'request': function (config) { config.headers = config.headers || {}; if ($sessionStorage.token) { config.headers.Authorization = $sessionStorage.token; } return config; }, 'responseError': function (response) { if (response.status === 401 || response.status === 403) { $location.path('/'); } return $q.reject(response); } }; }]); });
然后,我后端的中间件处理程序如下所示:
var router = express.Router(); // middleware to use for all requests router.use(function (req, res, next) { 'use strict'; res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); next(); }); //middleware to validate token router.use('/foos', function (req, res, next) { 'use strict'; var token = req.headers.authorization; console.log(token); authorizeRequest(token); next(); }); router.get('/foos', function (req, res) { 'use strict'; actividadController.getActividad(req, res); }); app.use('/api', router); app.listen(8080);
authorizeRequest函数调用Authentication API。
我的问题是两个中间件在每个请求上被调用两次,我找不到发生这种情况的原因。
看起来中间件是从OPTIONS
请求中被触发的。 使用像Cors这样更强大的快速库可以解决这个问题。
或者,您可以手动检查OPTIONS
请求,然后返回必要的信息而不是调用next()
,但是除非您确切知道您在做什么,否则我不会推荐。
祝你好运!
最后我通过http方法而不是url做了一个方法。
而不是router.use我使用路由器。 和一个正则expression式来描述这个uri。
router.get('/user/:username/*', function (req, res, next) { 'use strict'; var token = req.headers.authorization; http.get('http://localhost:10020/api/tokens/' + token, function (response) { if (response.statusCode === 200) { next(); } else { res.status(response.statusCode).json({ message: "Rejected" }); } }); });
- 未请求的Socket.IO连接
- 如何通过社交服务进行用户身份validation
- Firebase 3 node.js服务器authentication是否会改变?
- 成功login后,Azureauthentication返回到login页面 – node.js
- 只有一个用户login系统
- Sails.js Waterlock / auth / register导致错误500
- node.js – everyauth – Facebook API和会话处理
- 用户注销:将GETredirect到POST(Node / Express)
- NodeJS Passport:通过两种策略multilogin – 序列化问题