node-request 模块和我们平时用的 axios 的判定方式不通,所以特别记录一下。
示例代码:
1 2 3 4 5 6 7
| request("http://xxx/index.html", (err, response, body) => { if (err) { next(err); } else { res.send(body); } });
|
如果请求失败的话,例如 404,500 的情况,我原本以为需要到 error 对象中进行处理,例如这样:
1 2 3 4 5 6 7 8 9 10
| request("http://xxx/index.html", (err, response, body) => { if (err) { if (+err.status === 404) { } next(err); } else { res.send(body); } });
|
但实际上并不会,而是需要在 response 中进行判断:
1 2 3 4 5 6 7 8 9 10
| request("http://xxx/index.html", (err, response, body) => { if (err) { next(err); } else { if (+response.statusCode === 404 || +response.statusCode === 500) { } res.send(body); } });
|
其实这也比较好理解,只要源站有正常的响应,不论状态码是多少都可能当成正常返回了。只要当遇到请求超时,服务不通等情况才会进入到 err,这种情况是没有状态码的。