2017-11-18 72 views
0
async function checkToken(token) { 
    const result = await superagent 
    .post(`${config.serviceUrl}/check_token`) 
    .send({token}); 
    return result.body; 
} 

默认选项,如果这个调用将返回401抛出异常,这不是我所期望的。我打电话给我的API使用HTTP状态消息也作为身体来提供信息,我只需要身体部分。任何方式来获得4xx响应身体W/O尝试...赶上,而使用等待?

,HTTP状态为401的响应是

{ 
    "data": null, 
    "error": { 
     "code": "INVALID_TOKEN", 
     "message": "Token is not valid" 
    } 
} 

而目前,为了得到这一点,我需要包装所有的SuperAgent与尝试调用...赶上

async function checkToken(token) { 
    let result = null; 
    try { 
    result = await superagent 
     .post(`${config.serviceUrl}/check_token`) 
     .send({token}); 
    } catch (e) { 
    result = e.response; 
    } 
    return result.body; 
} 

任何方式有1样品工作和返回JSON没有看HTTP状态?

回答

1

SuperAgent的默认对待每个4XX和5xx响应的错误。但是,您可以通过使用.ok来告诉它,您认为哪些响应是错误的。从文档(https://visionmedia.github.io/superagent/#error-handling

样品例如,

request.get('/404') 
.ok(res => res.status < 500) 
.then(response => { 
    // reads 404 page as a successful response 
}) 

如果函数的.ok内,返回true,则它不会被认为是错误的情况下。

0

试试这个

async function checkToken(token) { 
 
    const result = await superagent 
 
    .post(`${config.serviceUrl}/check_token`) 
 
    .send({token}).then(v=>v).catch(v=>v); 
 
    return result.body; 
 
}