You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
graphResource2/test/koa修改code.md

40 lines
1.2 KiB

10 months ago
要在 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。