【问题标题】:Get status and data from request api by fetch in react native通过在 react native 中获取请求 api 的状态和数据
【发布时间】:2018-02-05 05:02:59
【问题描述】:

当使用此代码时,我尝试从 React Native 中的请求中提取数据和状态请求

function postUser(FirstName, LastName, Phone, Email, Password) {
    let data = {
        method: 'POST',
        credentials: 'same-origin',
        mode: 'same-origin',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            email: Email,
            password: Password,
            first_name: FirstName,
            last_name: LastName,
            phone: Phone
        })
    }
    return fetch(URLPostUser, data)
        .then(response => response.json())
} 

在这个结果中没有状态。

当更改函数的返回时,我尝试获取状态,但在这种情况下无权访问数据

function postUser(FirstName, LastName, Phone, Email, Password) {
    let data = {
        method: 'POST',
        credentials: 'same-origin',
        mode: 'same-origin',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            email: Email,
            password: Password,
            first_name: FirstName,
            last_name: LastName,
            phone: Phone
        })
    }
    return fetch(URLPostUser, data)
}

【问题讨论】:

    标签: javascript react-native fetch


    【解决方案1】:

    您可以执行以下操作

    return fetch(URLPostUser, data)
        .then(response => ({ response, json: response.json()}))
    

    现在承诺的对象是

    {
        response: // the response object
        json: // the parsed JSON
    }
    

    或者如果您不想要完整的响应

    return fetch(URLPostUser, data)
        .then(response => ({ status: response.status, json: response.json()}))
    

    结果是对象的承诺

    {
        status: // the response object
        json: // the parsed JSON
    }
    

    【讨论】:

      【解决方案2】:

      https://stackoverflow.com/a/39339648/8533250

      那些链接对我很有帮助。 因为之前回答返回

      { status: 200, json: Promise})

      【讨论】:

        猜你喜欢
        • 2020-04-25
        • 1970-01-01
        • 1970-01-01
        • 2016-01-11
        • 2021-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多