[英]Issues with axios POST requests (javascript) and Sinatra/Base API (ruby)
使用javascript庫axios嘗試向Ruby Sinatra / Base API發出POST請求時,我一直遇到問題
我在下面的Sinatra API中有一個示例POST路由,axios不斷給我帶來一般錯誤
# 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
使用axios庫的Java代碼:
// 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)
})
我在控制台中不斷收到通用javascript錯誤
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)
我的服務器端終端沒有給我任何更好的工作方式,它說選項帶有200狀態代碼,但是對於導致403錯誤的原因我卻一無所知...沒有參數使它成功進入我的路線...
::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
好,謝謝您,它可以通過以下解決方法為我工作:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.