简体   繁体   中英

React/Rails AJAX POST request returns 404

I'm trying to wire up this AJAX POST request in my react component to communicate with my rails api controller. The console logs a 404 error and I can't seem to hit the pry.

react/src/pages/HomeIndex.js

  getCompare() {
    $.ajax({
      url: '/api/sources/compare',
      type: 'POST',
      data: {value: this.state.inputValue, from: this.state.compareFrom, to: this.state.compareTo },
      contentType: 'application/json'
    })
  }

controllers/api/sources_controller.rb

  def compare
    binding.pry
  end

config/routes

  post '/api/sources/compare', to: 'api/sources#compare'

  namespace :api do
    resources :sources, only: [:index, :compare]
  end

rake routes

api_sources_compare POST /api/sources/compare(.:format) api/sources#compare

update

I tried updating the routes with several permutations...

  namespace :api do
    resources :sources, only: [:index] do
      collection do
        post :compare
      end
    end
  end

  namespace :api do
    resources :sources, only: [:index, :compare] do
      collection do
        post :compare
      end
    end
  end

  namespace :api do
    resources :sources, only: [:index] do
      collection do
        resources :compare, only: [:compare]
      end
    end
  end

  namespace :api do
    resources :sources do
      post :compare
    end
  end

...all with the same outcome.

You can solve this by stringifying your AJAX payload, as follows:

 getCompare() { let data = JSON.stringify({value: this.state.inputValue, from: this.state.compareFrom, to: this.state.compareTo }) $.ajax({ url: '/api/sources/compare', type: 'POST', data: data, contentType: 'application/json' }) } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM