alioth/before/cha/11=initkoa/test/koa修改code.md
2025-05-30 09:18:01 +08:00

40 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

要在 Koa 中修改 HTTP 响应的状态码(code),可以简单地通过 ctx.status 属性进行修改。例如,将响应状态码修改为 404
```js
app.use(async (ctx, next) => {
ctx.status = 404;
// 继续执行后续中间件,并在之后对响应进行修改
await next();
});
```
在上述代码中,我们将响应状态码设置为 404并在之后继续执行后续中间件。这意味着你可以在后续中间件中进一步修改响应内容比如设置响应体、设置 headers 等。
如果你想要在响应发送之前中止中间件的执行,可以通过 ctx.throw 方法或在抛出一个 Error 对象,同时设置其 status 或者 statusCode 属性:
```js
app.use(async (ctx, next) => {
if (someCondition) {
ctx.throw(400, 'Bad Request');
} else {
await next();
}
});
```
或者:
```js
app.use(async (ctx, next) => {
if (someCondition) {
const err = new Error('Bad Request');
err.status = 400;
throw err;
} else {
await next();
}
});
```
在上述代码中,当 someCondition 符合时,我们通过 ctx.throw 或抛出 Error 对象来中止中间件执行,并将响应状态码设置为 400。