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.
getCompare() {
$.ajax({
url: '/api/sources/compare',
type: 'POST',
data: {value: this.state.inputValue, from: this.state.compareFrom, to: this.state.compareTo },
contentType: 'application/json'
})
}
def compare
binding.pry
end
post '/api/sources/compare', to: 'api/sources#compare'
namespace :api do
resources :sources, only: [:index, :compare]
end
api_sources_compare POST /api/sources/compare(.:format) api/sources#compare
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.