React form возвращает 404, не найден при попытке зарегистрироваться через Devise Rails API - PullRequest
2 голосов
/ 06 февраля 2020

Я пытаюсь создать простую форму, которая позволяет пользователям регистрировать новую учетную запись, используя React JS и Ruby в Rails API. Я использую гем API разработки / разработки аутентификации для своей учетной записи. Я создал форму с реакцией, но когда я отправляю свою форму, она возвращает ошибку 404. Не найдено. enter image description here

Интересно то, что когда я использую почтальон для выполнения точно такого же запроса , он успешно регистрирует нового пользователя.

enter image description here

Я пытался подключить его к другим маршрутам, изменил тип запроса, но, похоже, ничего не работает. Я запускаю свое приложение React на порту 8080 и на рельсах 3000.

Вот мой текущий код:

import React, { Component } from "react";
import axios from "axios";

class Registration extends Component {
  constructor(props) {
    super(props);

    this.state = {
      email: "",
      password: "",
      password_confirmation: "",
      registrationErrors: ""
    };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    this.setState({
      [event.target.name]: event.target.value
    });
  }

  handleSubmit(event) {
    event.preventDefault();
    console.log("form submitted");
    const { email, password, password_confirmation } = this.state;
    axios
      .post(
        "/auth",
        {
          user: {
            email,
            password,
            password_confirmation
          }
        },
        { withCredentials: true }
      )
      .then(response => {
        console.log("registration res", response);
      })
      .catch(error => {
        console.log("egistration", error);
      });

    // axios returns a promise so need to use a then to convert it to json
    // then give out errors if there are any
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input
            type='email'
            name='email'
            placeholder='Email'
            value={this.state.email}
            onChange={this.handleChange}
            required
          />

          <input
            type='password'
            name='password'
            placeholder='Password'
            value={this.state.password}
            onChange={this.handleChange}
            required
          />

          <input
            type='password'
            name='password_confirmation'
            placeholder='Password Confirmation'
            value={this.state.password_confirmation}
            onChange={this.handleChange}
            required
          />

          <button type='submit'>Register</button>
        </form>
      </div>
    );
  }
}

export default Registration;


app / controllers / auth / registrations_controller.rb

module Auth
  class RegistrationsController < DeviseTokenAuth::RegistrationsController
    def new
      user = User.new
    end

    def create
      user = User.new(sign_up_params)
      if user.save
        render json: {status: "SUCCESS", message: "added a new user!", data: user}, status: :ok
      else
        render json: {status: "ERROR", message: "couldn't add a user", data: user.errors}, status: :unprocessable_entity
      end
    end

    private
    def sign_up_params
      params.permit(:name, :email, :password, :password_confirmation)
    end
    def account_update_params
      params.permit(:name, :email)
    end
  end
 end

Рельсовые маршруты

Rails.application.routes.draw do

  mount_devise_token_auth_for 'User', at: 'auth', controllers: {
    registrations: 'auth/registrations'
   }
end

         new_user_session GET    /auth/sign_in(.:format)                                                                  devise_token_auth/sessions#new
             user_session POST   /auth/sign_in(.:format)                                                                  devise_token_auth/sessions#create
     destroy_user_session DELETE /auth/sign_out(.:format)                                                                 devise_token_auth/sessions#destroy
        new_user_password GET    /auth/password/new(.:format)                                                             devise_token_auth/passwords#new
       edit_user_password GET    /auth/password/edit(.:format)                                                            devise_token_auth/passwords#edit
            user_password PATCH  /auth/password(.:format)                                                                 devise_token_auth/passwords#update
                          PUT    /auth/password(.:format)                                                                 devise_token_auth/passwords#update
                          POST   /auth/password(.:format)                                                                 devise_token_auth/passwords#create
 cancel_user_registration GET    /auth/cancel(.:format)                                                                   auth/registrations#cancel
    new_user_registration GET    /auth/sign_up(.:format)                                                                  auth/registrations#new
   edit_user_registration GET    /auth/edit(.:format)                                                                     auth/registrations#edit
        user_registration PATCH  /auth(.:format)                                                                          auth/registrations#update
                          PUT    /auth(.:format)                                                                          auth/registrations#update
                          DELETE /auth(.:format)                                                                          auth/registrations#destroy
                          POST   /auth(.:format)                                                                          auth/registrations#create
      auth_validate_token GET    /auth/validate_token(.:format)                                                           devise_token_auth/token_validations#validate_token
       rails_service_blob GET    /rails/active_storage/blobs/:signed_id/*filename(.:format)                               active_storage/blobs#show
rails_blob_representation GET    /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show
       rails_disk_service GET    /rails/active_storage/disk/:encoded_key/*filename(.:format)                              active_storage/disk#show
update_rails_disk_service PUT    /rails/active_storage/disk/:encoded_token(.:format)                                      active_storage/disk#update
     rails_direct_uploads POST   /rails/active_storage/direct_uploads(.:format)                                           active_storage/direct_uploads#create


Буду признателен за любые идеи.

ОБНОВЛЕНИЕ: Я попытался изменить номер порта моего приложения реагирования на 3000, а мой rails API на 3001, поскольку URL-адрес, введенный в почтальоне, был localhost 3000. Но все равно возвращается та же ошибка.

ОБНОВЛЕНИЕ 2: Ниже приведены вкладки сети.

enter image description here

enter image description here

ОБНОВЛЕНИЕ: В приложении есть заголовки почтальона и полезная нагрузка enter image description here enter image description here

1 Ответ

0 голосов
/ 06 февраля 2020

Я считаю, что проблема в теле топора ios. Вы отправляете поля внутри пользовательского ключа json, а не указываете ключи для других полей. Попробуйте удалить этот ключ и просто отправить электронное письмо, пароль и подтверждение пароля.

Например:

axios.post("/auth", {
            email: email,
            password: password,
            password_confirmation: password_confirmation
          },
        { withCredentials: true }
      )

Если это не сработает, это может быть связано с опцией withCredentials.

В любом случае, посмотрите на AX ios 'документы, чтобы увидеть его параметры https://github.com/axios/axios

Вы можете использовать вкладку Сеть, чтобы проанализировать отправленный запрос и увидеть, как параметры и заголовки отличаются от тех, что на почтальоне.

...