简体   繁体   中英

Why node js middleware using Express after successful authorization does not call given API?

I have below setup to call API with middleware to authorize it before success.

  1. Calling API with token i d with header object using jquery ajax,
 $.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 } });
  1. Setting node server as below,
 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')); ...
  1. setting API in modelApi/index.js,
 var express = require('express'), router = express.Router(), api = require('../api.js'), router.post('/api/auth/fetchMycontent', api.fetchMycontent); module.exports = router;
  1. middleware.js file will be like
 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, } }); } }, };
  1. From api.js,fetchMycontent function will be like
 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM