I have managed to make middleware work in Strapi. But, I can't see the body in the request.
Inside /middlewares/getEmail/index.js, I Have
module.exports = (strapi) => {
return {
initialize: function (cb) {
strapi.app.use(async (ctx, next) => {
if (ctx.method === "POST" && ctx.url === "/email-leads") {
console.log(ctx);
}
await next();
});
},
};
};
and ctx request logs:
request: {
method: 'POST',
url: '/email-leads',
header: {
'content-type': 'application/json',
accept: 'application/json',
'user-agent': 'PostmanRuntime/7.26.8',
'postman-token': 'xxx',
host: 'localhost:1337',
'accept-encoding': 'gzip, deflate, br',
connection: 'keep-alive',
'content-length': '33'
}
},
This is the only middleware I have written on this application. In the /config/middleware.js, I have
module.exports = {
load: {
before: ["getEmail", "responseTime", "logger", "cors", "responses", "gzip"],
order: ["parser"],
after: ["router"],
},
settings: {
getEmail: {
enabled: true,
},
},
};
I read about this koa-body/unparsed.js to read the body but there's literally no body in the ctx.request. Thanks for help.
So, I have reached a solution. Posting here in case anyone else needs it.
In config/middleware.js
, I have changed the load, taking the custom middleware to after
array.
load: {
before: ["responseTime", "logger", "cors", "responses", "gzip"],
after: ["parser", "router", "getEmail"],
},
I still can't see the ctx.request.body
if I log ctx
or ctx.request
. But, if I use ctx.request.body
directly, I can reach it in case the load is written as above (or custom middleware after parser
).