首页 > 解决方案 > React Native:在简单的发布请求上使用 RxJS 的 Ajax 错误

问题描述

我正在尝试使用我也用于我的网站的模块在 React Native 中执行一个简单的发布请求。

我有一个 api.ts 文件,其中定义了以下内容:

import { ajax } from 'rxjs/observable/dom/ajax';
import { AjaxRequest } from 'rxjs/observable/dom/AjaxObservable';

 const ApiClient = {

  loginUser: (email: string, password: string) => {
    let requestBody = {email, password};
    let url = `${dotenv.REACT_APP_API_URL}/api/users/login`;
    return createRequestOptions(url, HttpOptions.POST, requestBody);
  }
 }

请求选项方法如下:

const createRequestOptions = (url: string, method: string, requestBody?: object) => {

    let requestOptions: AjaxRequest = {
      method: method,
      url: url,
      crossDomain: true,
      responseType: 'json',
      headers: {
        'Content-Type': 'application/json',
      }
    };
    if ((method === HttpOptions.POST || method === HttpOptions.PUT) && requestBody) {
      requestOptions.body = requestBody;
    }

    console.log(requestOptions);

    return ajax(requestOptions);
};

requestOptions 的输出如下:

Object {
  "body": Object {
    "email": "myemail@gmail.com",
    "password": "mypassword",
  },
  "crossDomain": true,
  "headers": Object {
    "Content-Type": "application/json",
  },
  "method": "POST",
  "responseType": "json",
  "url": "http://localhost:3001/api/users/login",
}

最后在我的史诗中,我有以下内容:

const authLoginEpic: Epic = (action$, store) =>
  action$.pipe(
    ofType(ActionTypes.AUTH_LOGIN_REQUEST),
    mergeMap((action: AuthLoginRequest) =>
      ApiClient.loginUser(action.payload.username, action.payload.password).pipe(
        map((res: any) => {
          return AuthLoginReceive.create({response: res.response, email: action.payload.username});
        }),
        catchError((err) => {
          console.log(JSON.stringify(err));

出于某种原因,触发了 catchError,我不知道为什么会这样。日志的输出是:

{"message":"ajax error","name":"AjaxError","xhr":{"UNSENT":0,"OPENED":1,"HEADERS_RECEIVED":2,"LOADING":3,"DONE":4,"readyState":4,"status":0,"timeout":0,"withCredentials":false,"upload":{},"_aborted":false,"_hasError":true,"_method":"POST","_response":"","_url":"http://localhost:3001/api/users/login","_timedOut":false,"_trackingName":"unknown","_incrementalEvents":false,"_requestId":null,"_cachedResponse":null,"_headers":{"content-type":"application/json"},"_responseType":"json","_sent":true,"_lowerCaseResponseHeaders":{},"_subscriptions":[]},"request":{"async":true,"crossDomain":true,"withCredentials":false,"headers":{"Content-Type":"application/json"},"method":"POST","responseType":"json","timeout":0,"url":"http://localhost:3001/api/users/login","body":"{\"email\":\"mymail@gmail.com\",\"password\":\"mypassword\"}"},"status":0,"responseType":"json","response":null}

Ajax 错误的描述性不是很强。有人我可能做错了吗?

标签: react-nativerxjs

解决方案


似乎这是因为 api 地址设置为 localhost 或 127.0.0.1 的简​​单事实

确保已将此设置为您的本地网络 IP 地址!


推荐阅读