对 Rails 敲门反应 Axios

React Axios to Rails Knock

我正在尝试使用 React 前端中的以下函数将 POST 请求从 axios 发送到 Rails API:

  export function registerUser({ name, email, password }) {
    var postdata = JSON.stringify({
      auth: {
        name, email, password
        }
      });
    return function(dispatch) {
      axios.post(`${API_URL}/user_token`, postdata )
      .then(response => {
        cookie.save('token', response.data.token, { path: '/' });
        dispatch({ type: AUTH_USER });
        window.location.href = CLIENT_ROOT_URL + '/dashboard';
      })
      .catch((error) => {
        errorHandler(dispatch, error.response, AUTH_ERROR)
      });
    }
  }

Knock gem 需要以下格式的请求:

{"auth": {"email": "foo@bar.com", "password": "secret"}}

我当前的函数似乎生成了正确的格式(在浏览器开发工具中检查请求),但我收到以下错误:

Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {data, status, statusText, headers, config, request}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of Register.

class Register extends Component {
  handleFormSubmit(formProps) {
    this.props.registerUser(formProps);
  }

  renderAlert() {
    if(this.props.errorMessage) {
      return (
        <div>
          <span><strong>Error!</strong> {this.props.errorMessage}</span>
        </div>
      );
    }
  }

  render() {
    const { handleSubmit } = this.props;

    return (
      <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
      {this.renderAlert()}
      <div className="row">
        <div className="col-md-6">
          <label>Name</label>
          <Field name="name" className="form-control" component={renderField} type="text" />
        </div>
      </div>
        <div className="row">
          <div className="col-md-12">
            <label>Email</label>
            <Field name="email" className="form-control" component={renderField} type="text" />
          </div>
        </div>
        <div className="row">
          <div className="col-md-12">
            <label>Password</label>
            <Field name="password" className="form-control" component={renderField} type="password" />
          </div>
        </div>
        <button type="submit" className="btn btn-primary">Register</button>
      </form>
    );
  }
}

错误是由您代码中的以下行引起的

errorHandler(dispatch, error.response, AUTH_ERROR)

引发的异常清楚地解释了这一点。不要设置 error.response,而是尝试使用来自 error.response 的实际数据。例如 error.response.data。此外,您可以尝试用字符串替换 error.response 并查看它的行为,然后从 error.response.data.

中引用您需要的字符串