在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:jeffijoe/koa-respond开源软件地址:https://github.com/jeffijoe/koa-respond开源编程语言:JavaScript 100.0%开源软件介绍:koa-respondMiddleware for Koa that adds useful methods to the Koa context. Installationnpm install --save koa-respond Usage// Install it
const respond = require('koa-respond');
// For Koa v2 - if you are looking for v1, scroll to the bottom.
app.use(respond());
// Use it
app.use((ctx) => {
// Sets status to 200 and the body to `{ id: 123, name: 'Dat Boi' }`
ctx.ok({ id: 123, name: 'Dat Boi' });
// Both of these set status to 404 and
// the body to `{ message: 'Not found, boii' }`
ctx.notFound('Not found, boii');
ctx.notFound({ message: 'Not found, boii' });
// And everyone's favorite..
ctx.badRequest({ error: 'missing input' });
// Or if you prefer to do it yourself..
// Both of these send a HTTP 201 with a body
// of `{ message: 'new beginnings!' }`
ctx.send(201, 'new beginnings!');
ctx.send(201, { message: 'new beginnings!' });
}); MethodsAll methods call the
If you wish to disable the automatic wrapping of strings globally, you can instantiate app.use(respond({
autoMessage: false
})) All functions return the Koa context itself (chainable) ctx.ok().set({ 'X-Some-Header': 'awesome' }) All functions are also bound to the context. This means you can pass the function as a reference without having to bind it first. app.use((ctx) => somePromiseCall().then(ctx.ok)) Available methods
Does this work for Koa 1?Not out of the box, because it's time you move on to v2. To use const respond = require('koa-respond');
// Middleware to install koa-respond.
app.use(function *(next) {
respond().patch(this);
yield next;
});
// Now the methods are available.
app.use(function *() {
this.ok({ id: 123, name: 'Bob' });
}); Adding additional methodsIf you feel like some methods are missing, you can add them yourself, like so: app.use(respond({
statusMethods: {
imATeapot: 418,
enhanceYourCalm: 420
}
}));
app.use((ctx) => {
ctx.imATeapot('Hello, a Teapot I am.');
ctx.enhanceYourCalm({ todo: 'blaze it' });
}); Even more custom methodsIf you just want to add shortcuts without adding an additional middleware, you can do that, too. app.use(respond({
methods: {
shizzle: (ctx, message) => {
ctx.send(200, message + ', fo-shizzle');
}
}
}));
app.use((ctx) => {
// HTTP 200 { message: 'Koa is the best, fo-shizzle' }
ctx.shizzle('Koa is the best');
}); Contributing
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论