我有一个 axios 代码,它调用一个返回 302 和一个Location:标头的端点。我正在编写一个测试,该测试应该评估方法响应并确认正确的(HTTP 302)响应以及检查Location:URL 内容。
所以我有一个测试代码(开玩笑)
let axiosReply = await axios.get(this.redirectUrl, {
maxRedirects: 0 // do not follow redirects...
});
expect(axiosReply.status).toBe(302);
// some checks of header Location: follow
Run Code Online (Sandbox Code Playgroud)
但是,axios 会抛出错误:
Error: Request failed with status code 302
at createError (C:\<my project folder>\node_modules\axios\lib\core\createError.js:16:15)
at settle (C:\<my project folder>\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (C:\<my project folder>\node_modules\axios\lib\adapters\http.js:260:11)
at IncomingMessage.emit (events.js:215:7)
at endReadableNT (_stream_readable.js:1184:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
Run Code Online (Sandbox Code Playgroud)
如何配置 Axios 只返回回复而不抛出错误?
为了不这样做throw,请使用valudateStatus选项:
result = await axios.get(this.url, {
validateStatus: function (status) {
// if this function returns true, exception is not thrown, so
// in simplest case just return true to handle status checks externally.
return true;
}
});
if (result.status === StatusCodes.FORBIDDEN) {
// react on a 403 error in a custom way
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3630 次 |
| 最近记录: |