【问题标题】:TypeError: Network request failed using fetch ReactNative and Laravel responseTypeError:网络请求使用 fetch ReactNative 和 Laravel 响应失败
【发布时间】:2020-01-09 03:27:06
【问题描述】:

我正在向 Laravel 发布数据并期望得到成功响应,但它捕获了异常 TypeError: Network request failed使用 Laravel 护照的 get 方法和 login post 方法都可以正常工作。

  • 将 'Content-Type': 'application/json' 添加到标头会导致登录方法的网络请求失败。
  • Postman 返回有效错误或成功,因此完全按预期工作。
  • 调试显示请求已发送到 Laravel,并且路由正确,因为 Visual Studio Code 调试器在返回响应的断点处停止。
public function postMessages()
{
    ...

    return response()->json(['success' => 'success'], 200);
}
Route::middleware('auth:api')->group(function () {
    Route::post('messages', 'Api\ChatController@postMessages');
});
export const fetchApi = async (endPoint, method = 'get', body = {}) => {
    const accessToken = authSelectors.get().tokens.access.value;
    const accessType = authSelectors.get().tokens.access.type;
    let headers = {
      ...(accessToken &&
      {
        Authorization: `${accessType} ${accessToken}`
      } 
      )
    };
    let response;
    if (method=='get' || Object.keys(body)==0 ) {
        response = await fetch(`${apiConfig.url}${endPoint}`, {
            method: method,
            headers: headers
        });
    } else {
        var formData = new FormData();
        Object.keys(body).forEach(type => {
            formData.append(type, body[type]);
        });
        response = await fetch(`${apiConfig.url}${endPoint}`, {
            method: method,
            headers: headers,
            body: formData
        });
        console.log('fetch response: ' + JSON.stringify(response));
    }
    let responseJsonData = await response.json();
    return responseJsonData;
}
export const postMessages = (eidug, type, name, messages) => fetchApi('/message', 'post', {
    'eidug': eidug,
    'type': type,
    'name': name,
    'messages': messages
});

我希望像 Postman 一样毫无例外地做出回应。可能出了什么问题?

【问题讨论】:

    标签: php laravel react-native request postman


    【解决方案1】:

    您是否在后端启用了 CORS?一旦打开检查-> 网络,然后运行 ​​fetch。显示是否有任何错误。

    【讨论】:

    • 登录的发布方法正在工作。我使用了一些库来发送响应(IssueTokenTrait)。这些方法的状态为 200,responseContenType: application/json, responseHeaders, ... response()->json(['success' => 'success'], 200);arrives 的状态为 0,reponse null,inspect 网络中没有 responseHeaders。
    • 没有必要使用任何 cors 中间件。在使用 Laravel Passport 和 API 令牌验证时,这可能是正常的。问题似乎是缺少参数。验证函数没有给出任何明确的错误,但是缺少消息参数,因为我没有使用 JSON.stringify 将数组从 react-native 传递给 laravel ......有点奇怪,它没有进入 error_log,但它是解决了:)
    猜你喜欢
    • 2022-01-14
    • 1970-01-01
    • 2019-02-09
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 2022-01-12
    相关资源
    最近更新 更多