-
Notifications
You must be signed in to change notification settings - Fork 87
Middleware example: a custom response for login requests
Lloyd Brookes edited this page Feb 16, 2022
·
1 revision
Probably the most simple way to create a custom response is to create a quick middleware plugin.
Simple plugin to demonstrate handling a login request:
class Example {
middleware (config) {
return async (ctx, next) => {
if (ctx.request.path === '/login' && ctx.request.method === 'POST') {
const { username, password } = ctx.request.body
if (password === '123') {
ctx.response.body = `Welcome ${username}`
} else {
ctx.response.body = `Wrong password`
}
}
await next()
}
}
}
export default Example
Save it to example.js
then launch a server. The order of middleware plugins passed to --stack
is significant - in this example, lws-body-parser
is included before example.js
- this ensures the request body has been parsed and made available on ctx.request.body
before the example middleware is invoked.
$ ws --stack lws-log lws-body-parser tmp/example.js -f dev
Make some test requests..
$ curl http://127.0.0.1:8000/login -d '{ "username": "Lloyd" }' -H 'content-type: application/json'
Wrong password
$ curl http://127.0.0.1:8000/login -d '{ "username": "Lloyd", "password": "123" }' -H 'content-type: application/json'
Welcome Lloyd