koajs / bodyparser

Koa body parsing middleware
MIT License
1.31k stars 117 forks source link

Replace body content #138

Closed simplenotezy closed 1 year ago

simplenotezy commented 4 years ago

Problem/Feature Request Summary

I'd like to run a "replace()" function on the body content, replacing any string I'd like. But I am not sure how.

I have tried like so:

class ReplaceURLs {
  middleware () {
    return async (ctx, next) => {
            await next();
            if (ctx.response.body) {
                ctx.response.body = ctx.response.rawBody.replace('somestring','somethingelse');
            }
    }
  }
}

module.exports = ReplaceURLs

But it doesn't work.

What am I missing here?

3imed-jaberi commented 1 year ago

Hey @simplenotezy, I see you have a typo in your example. You need to replace 'ctx.response.rawBody' with 'ctx.request.rawBody' and you need to replace the checking in the if condition too.

I'll close the issue, feel free to ping me or re-open it.