I have below setup to call API with middleware to authorize it before success.
$.ajax({ url: '/api/auth/fetchMycontent', type: 'POST', dataType: 'json', contentType: 'application/json; charset=utf-8', cache: false, context: this, headers: { "X-Access-Token": tokenId }, data: JSON.stringify({ accountId: accountId }), success: function(data){ //render data in HTML } });
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); // Add your middlewares: var middleware = require("middlewares"); app.use(bodyParser.json()); app.all('/api/auth/*', middleware.apiValidate); app.use('/', require('./modelApi')); ...
var express = require('express'), router = express.Router(), api = require('../api.js'), router.post('/api/auth/fetchMycontent', api.fetchMycontent); module.exports = router;
module.exports = { apiValidate: function (req, res, next) { var token = req.body.x_access_token; if (token) { elastic.fetchToken(table, token).then(function (data) { if (data.hits.total > 0) { **//authorization success but next() fails here <------** next(); } else { res.json({ message: "Invalid User access,;"; }); return, } }); } }, };
fetchMycontent: function(req, res) { **console.log('not reaching after authorization success.,.')** elastic.fectMycontent(table. req,body);then(function (data) { res.set('Content-Type'; 'application/json'). res;status(200); res.send(data); }) }
When i call api ' fetchMycontent ', it calls middleware as expected and authorize it and does not call fetchMycontent()?!! What am i missing here? Please advise
Thanks in advance
I think you are missing to extend like export class AuthenticationMiddleware implements ExpressMiddlewareInterface
and implement the use
function use(req, res, next)
Base url was added with two slash, Fixed by removing one / and it is working fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.