繁体   English   中英

获取 API 返回 json object 或响应状态

[英]Fetch API return json object or response status

我对获取 API 有点困惑。这是一个简单的登录 function

export default class LoginService {
    async loginUser(u, p) {
        return fetch(API_URL + '/users/authenticate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 'username': u, 'password': p })
        })
            .then(response => response.json())
            .catch(e => console.log(e))
        }
}

当找不到用户时,在后端返回 400 错误请求。 如何返回 json object 或响应状态? 或者这种做法是错误的?

谢谢!

如何返回 json object 或响应状态?

ok响应属性为您提供 HTTP 调用的高级“有效/无效”( fetch仅拒绝其 promise网络错误,而不是 HTTP 错误 - api 中的脚枪,您经常看到人们发生冲突)。

我不会返回响应状态,我会将其包含在async function 抛出的错误中。我通常这样做:

async loginUser(u, p) {
    return fetch(API_URL + '/users/authenticate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 'username': u, 'password': p })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error ${response.status}`};
        }
        return response.json();
    }); // Note: No `catch` here!
}

但如果你真的想退货

async loginUser(u, p) {
    return fetch(API_URL + '/users/authenticate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 'username': u, 'password': p })
    })
    .then(response => {
        if (!response.ok) {
            return {failed: true, status: response.status};
        }
        return response.json();
    })
    .catch(e => console.log(e));
}

不过,以这种方式将拒绝转化为满足通常不是最佳做法。

    .then(res=>{
    if(res.ok)
    {
       return response.json()
    }
    else{
    // return 400 bad request here
    }
    })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM