简体   繁体   中英

Adding Custom Middlewares in Strapi

I am creating a custom middleware for strapi that will change the response body to the hash. I need to use this middleware for all routes in strapi, means on the application level.

'use strict';

/**
 * `ctx-decrypt` middleware.
 */

var crypto = require('crypto');

const algorithm = 'aes-256-cbc';

function decrypt(text,key) 
{
   let iv = Buffer.from(text.iv, 'hex');
   
   let encryptedText = Buffer.from(text.encryptedData, 'hex');
   
   let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);
   
   let decrypted = decipher.update(encryptedText);
   
   decrypted = Buffer.concat([decrypted, decipher.final()]);
   
   return decrypted.toString();
}

function hash(data)
{
  var hash = crypto.createHash('sha256', data);

  return hash;
}

module.exports = (config,{env},{strapi}) => 
{
  return 
  {
    initialize() 
    {
      strapi.app.use(async (ctx, next) => 
      {

        strapi.log.info('In ctx-decrypt middleware.');

        var ENC_KEY = process.env.ENC_KEY;
        
        var requestBody = ctx.request.body;
        //var responseBody = ctx.body;

        var dc = decrypt(requestBody,ENC_KEY);

        if(!dc)
        {
           throw new Error('Invalid request body!');

           ctx.response.set(hash("5u5234803riqifn"));

           console.log(ctx.body)
           
           await next();
        }
        
        else
        {
           ctx.response.set(hash("5u5234803riqifn"));

           console.log(ctx.body)
           
           await next();
        }

      });

    }

  };

};

Now I followed their latest docs but strapi always give some errors on using that middleware. I ran

npx strapi generate 

to generate middleware at the root of project. and then I ran

npx strapi middlewares:list

to get all the middleware names, then added my 'global::ctx-decrypt' middleware name in the./config/middlewares.js like this

module.exports = [
  'strapi::errors',
  'strapi::security',
  'strapi::cors',
  'strapi::poweredBy',
  'strapi::cors',
  'strapi::logger',
  'strapi::query',
  'strapi::body',
  'strapi::session',
  'strapi::favicon',
  'strapi::public',
  'global::ctx-decrypt',
];

it is giving me error like this

0|super-fu | [2022-12-23 02:48:51.181] debug: ⛔️ Server wasn't able to start properly.
0|super-fu | [2022-12-23 02:48:51.183] error: Middleware "global::ctx-decrypt": Cannot destructure property 'strapi' of 'undefined' as it is undefined.
0|super-fu | Error: Middleware "global::ctx-decrypt": Cannot destructure property 'strapi' of 'undefined' as it is undefined.
0|super-fu |     at instantiateMiddleware (/home/blackhole/nodejs/super-funnels/super-funnels-backend/node_modules/@strapi/strapi/lib/services/server/middleware.js:12:11)
0|super-fu |     at resolveMiddlewares (/home/blackhole/nodejs/super-funnels/super-funnels-backend/node_modules/@strapi/strapi/lib/services/server/middleware.js:56:18)
0|super-fu |     at registerApplicationMiddlewares (/home/blackhole/nodejs/super-funnels/super-funnels-backend/node_modules/@strapi/strapi/lib/services/server/register-middlewares.js:66:29)
0|super-fu |     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
0|super-fu |     at async Object.initMiddlewares (/home/blackhole/nodejs/super-funnels/super-funnels-backend/node_modules/@strapi/strapi/lib/services/server/index.js:99:7)
0|super-fu |     at async Strapi.bootstrap (/home/blackhole/nodejs/super-funnels/super-funnels-backend/node_modules/@strapi/strapi/lib/Strapi.js:414:5)
0|super-fu |     at async Strapi.load (/home/blackhole/nodejs/super-funnels/super-funnels-backend/node_modules/@strapi/strapi/lib/Strapi.js:426:5)
0|super-fu |     at async Strapi.start (/home/blackhole/nodejs/super-funnels/super-funnels-backend/node_modules/@strapi/strapi/lib/Strapi.js:169:9)
0|super-fu | 
0|super-fu | > super-funnels-backend@0.1.0 start
0|super-fu | > strapi start

How can I resolve this and use this middleware.

According to the docs, the correct function definition for middleware is as follows:

module.exports = (config, { strapi })=> {
  return (context, next) => {};
};

There is no third parameter so perhaps try {env, strapi} ?

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