React Native:在简单的帖子请求中出现RxJS的Ajax错误

时间:2019-05-11 10:52:21

标签: react-native rxjs

我正在尝试使用我也用于我的网站的模块在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错误不是非常描述性的。有人可能我做错了吗?

1 个答案:

答案 0 :(得分:0)

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

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