【问题标题】:Fetch request always returns network error获取请求总是返回网络错误
【发布时间】:2018-08-09 05:44:46
【问题描述】:

我几乎完成了 React Native 应用程序的创建,几天前注册操作已停止工作.. 我正在发送 fetch 请求,它总是返回网络错误,尽管有 400 响应和用户存在的消息,它停在那里..

我正在解构响应并显示 api 响应消息而不是获取网络错误,但现在它不起作用。我正在为登录操作做同样的事情。

可能是多部分/表单数据的东西吗?

export const register = data => dispatch => {
    dispatch(createUser());
    const d = new FormData();
    d.append("name", data.name);
    d.append("email", data.email);
    d.append("password", data.password);
    d.append("avatar", data.avatar);
    fetch(API_URL + "/register", {
        method: "POST",
        headers: {
            "content-type": "multipart/form-data"
        },
        body:d
    })
    .then(response => response.json().then(user => ({ user, response })))
    .then(({ user, response }) => {
        if (!response.ok) {
            console.log(response, user)
        } else {
            console.log(response, user)
        }
    })
    .catch(err => {
        throw err;
    });
};

api 路由在 Postman 中工作..

【问题讨论】:

  • 控制台中有更多信息吗?也许这是一个 CORS 错误(邮递员不需要 CORS,所以它可以在那里工作)?
  • 添加了mode 来获取请求但什么也没有,我的后端有app.use(cors())..

标签: reactjs react-native request fetch


【解决方案1】:

在这种情况下,您使用的基于 Promise 的 fetch 不正确,

试试,

fetch(API_URL + "/register", {
    method: "POST",
    headers: { "content-type": "multipart/form-data" },
    body:d
})
.then(response => {
      console.log(response, response.json().user)
})
.catch(err => {
    console.log(err)
});

检查日志,看看它是否显示正确的网络响应并从那里调试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 2013-01-21
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多