2017-05-08 25 views
1

我不斷收到問題與使用JavaScript庫Axios公司問題與愛可信POST請求(JavaScript的)和西納特拉/基礎API(紅寶石)

我有一個例子POST途徑試圖POST請求我的紅寶石西納特拉/基礎API下面我西納特拉API,愛可信一直採用愛可信庫給我一般錯誤

# 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 

我的JavaScript代碼:

// 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埃羅中的R我的控制檯

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錯誤...沒有PARAMS使其成功打入我的路線......

::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 
+0

嗨!你能解決嗎?我現在有同樣的問題,我donte得到idiea如何解決:( – Icaro

+0

@Icaro我不記得如果我得到了這個解決,我最終放棄了Sinatra和學習葡萄,它的光年比Sinatra更好,並提供更好的方式API功能 – aronlmin

回答

1

很好,謝謝你,我的作品與此變通辦法:

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 
相關問題