简体   繁体   English

为什么在成功授权后使用 Express 的节点 js 中间件不会调用给定 API?

[英]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.我有下面的设置来调用 API 与中间件在成功之前授权它。

  1. Calling API with token i d with header object using jquery ajax, 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,在modelApi/index.js中设置API,
 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 middleware.js 文件会像
 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从 api.js,fetchMycontent function 会像
 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()?!!当我调用 api ' fetchMycontent ' 时,它按预期调用中间件并对其进行授权并且不调用 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)我认为您缺少像export class AuthenticationMiddleware implements ExpressMiddlewareInterface并实现use function use(req, res, next)这样的扩展

Base url was added with two slash, Fixed by removing one / and it is working fine.基础 url 添加了两个斜线,通过删除一个 / 进行修复,它工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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