gpt4 book ai didi

javascript - axios POST 请求(javascript)和 Sinatra/Base API(ruby)的问题

转载 作者:行者123 更新时间:2023-11-30 15:20:11 25 4
gpt4 key购买 nike

在尝试使用 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

最佳答案

好吧,谢谢,这个解决方法对我有用:

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

关于javascript - axios POST 请求(javascript)和 Sinatra/Base API(ruby)的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43856293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com