【问题标题】:Issues with axios POST requests (javascript) and Sinatra/Base API (ruby)axios POST 请求 (javascript) 和 Sinatra/Base API (ruby) 的问题
【发布时间】:2017-10-06 23:11:42
【问题描述】:

我一直在尝试使用 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 库的 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 错误

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

【问题讨论】:

  • 嗨!你能解决这个问题吗?我现在有同样的问题,我不知道如何解决:(
  • @Icaro 我不记得我是否解决了这个问题,我最终放弃了 Sinatra 并学习了 Grape,它比 Sinatra 好几年,并提供了更好的 API 功能

标签: javascript ruby sinatra axios


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-05
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多