如何从React客户端向rails后端发送POST请求? (ActionController :: RoutingError(没有路由与[POST]匹配)

时间:2019-03-27 00:55:45

标签: ruby-on-rails reactjs routes

我正在开发React前端/ Rails后端应用程序,并且正在开发用户的登录名。为此,我从客户端向后端执行POST请求。但是,我遇到了RoutingError,但是我无法弄清楚为什么在运行rake路由时我的路由看起来很好

我尝试使用fetch函数参数来解决该问题,但是什么也没做。

我的提取功能:

fetch("http://localhost:3000/users/create", {
      method: "POST",
      mode: "no-cors",
      cache: "no-cache",
      credentials: "same-origin",
      headers: {
          "Content-Type": "application/json"
      },
      body: JSON.stringify({
          email: this.state.email,
          password: this.state.password
      })
    })
    .then(response => response.json())
    .then(response => {
      console.log(response)
    })

我的路线:

Rails.application.routes.draw do

  resources :meals, only: [:index]

  resources :users, only: [:new, :create]

end

我的users_controller:

class UsersController < ApplicationController

    def new
        @user = User.new

    end

    def create
        @user = User.new(params)
        @user.save
        render json: @user, status: 201

    end

end

我希望通过发布请求进入localhost:3000 / users / create,但是却收到以下错误消息:

Started POST "/users/create" for 127.0.0.1 at 2019-03-26 20:44:13 -0400
   (0.6ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
  ↳ /var/lib/gems/2.5.0/gems/activerecord-5.2.2.1/lib/active_record/log_subscriber.rb:98

ActionController::RoutingError (No route matches [POST] "/users/create"):

actionpack (5.2.2.1) lib/action_dispatch/middleware/debug_exceptions.rb:65:in `call'
actionpack (5.2.2.1) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
railties (5.2.2.1) lib/rails/rack/logger.rb:38:in `call_app'
railties (5.2.2.1) lib/rails/rack/logger.rb:26:in `block in call'
activesupport (5.2.2.1) lib/active_support/tagged_logging.rb:71:in `block in tagged'
activesupport (5.2.2.1) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (5.2.2.1) lib/active_support/tagged_logging.rb:71:in `tagged'
railties (5.2.2.1) lib/rails/rack/logger.rb:26:in `call'
actionpack (5.2.2.1) lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
actionpack (5.2.2.1) lib/action_dispatch/middleware/request_id.rb:27:in `call'
rack (2.0.6) lib/rack/runtime.rb:22:in `call'
activesupport (5.2.2.1) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
actionpack (5.2.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (5.2.2.1) lib/action_dispatch/middleware/static.rb:127:in `call'
rack (2.0.6) lib/rack/sendfile.rb:111:in `call'
railties (5.2.2.1) lib/rails/engine.rb:524:in `call'
puma (3.12.0) lib/puma/configuration.rb:225:in `call'
puma (3.12.0) lib/puma/server.rb:658:in `handle_request'
puma (3.12.0) lib/puma/server.rb:472:in `process_client'
puma (3.12.0) lib/puma/server.rb:332:in `block in run'
puma (3.12.0) lib/puma/thread_pool.rb:133:in `block in spawn_thread'

感谢您的帮助!

0 个答案:

没有答案