Reputation: 2572
I keep getting issues with attempting POST requests to my Ruby Sinatra/Base API using the javascript library axios
I have an example POST route in my Sinatra API below, axios keeps giving me generic errors
# Running on http://localhost:9292
class Endpoints < Sinatra::Base
register Sinatra::MultiRoute
before do
headers 'Access-Control-Allow-Origin' => 'http://localhost:8080',
'Access-Control-Allow-Methods' => ['OPTIONS', 'GET', 'POST'],
'Access-Control-Allow-Headers' => ['Content-Type']
end
options '*' do
headers 'Access-Control-Allow-Origin' => 'http://localhost:8080',
'Access-Control-Allow-Methods' => ['OPTIONS', 'GET', 'POST'],
'Access-Control-Allow-Headers' => ['Content-Type']
end
route :post, :options, '/create' do
# does something with params and return a JSON object
end
end
My Javascript Code using the axios library:
// Running on http://localhost:8080
axios.post('http://localhost:9292/create', {
some_val: 'some value'
})
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
})
I keep getting a generic javascript error in my console
POST http://localhost:9292/create 403 (Forbidden) bundle.js:20263
Error: Request failed with status code 403
at createError (bundle.js:12159)
at settle (bundle.js:19627)
at XMLHttpRequest.handleLoad (bundle.js:11996)
my server side terminal doesnt give me anything better to work with, it says the options passed with a 200 status code, but gives me nothing as far as what caused the 403 error... no params make it successfully into my route...
::1 - - [08/May/2017:12:49:35 -0700] "OPTIONS /create HTTP/1.1" 200 - 0.0030
::1 - - [08/May/2017:12:49:35 -0700] "POST /create HTTP/1.1" 403 30 0.0076
Upvotes: 1
Views: 470
Reputation: 497
well, thank you, it works for me with this workaround:
before do
if request.request_method == 'POST'
body_parameters = request.body.read
begin
data= params.merge!(JSON.parse(body_parameters))
@can_parse = true
rescue
puts "LOG: cant parse params" #TODO add real logger
@can_parse = false
end
end
Upvotes: 2