你好,这是我的第一篇帖子!
我试着调试这个问题已经有几天了,但无法解决。当我向rails api发出post请求时,我收到了以前从未见过的错误:
Started POST "/owners" for ::1 at 2021-01-12 11:24:15 -0500
(1.0ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Processing by OwnersController#create as */*
Parameters: {"email"=>"adam", "password"=>"[FILTERED]", "owner"=>{"email"=>"adam"}}
HTTP Origin header (http://localhost:3000) didn't match request.base_url (http://localhost:3001)
Completed 422 Unprocessable Entity in 0ms (ActiveRecord: 1.8ms | Allocations: 476)
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
就像我说的,我从来没有见过这样的事情,我也不知道我是怎么造成的。我没有使用代理服务器,我在这个项目中尝试的唯一新东西可能会搞砸事情,那就是我安装了devise,但决定不使用它并删除它。
我尝试过的事情:
确保我没有待处理的迁移:
检查我的路线:
Rails.application.routes.draw do
resources :owners
resources :dogs
post 'login', to: 'sessions#create'
end
然后我想这可能是cors的问题:
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Backend
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
config.api_only = true
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource(
'*',
headers: :any,
methods: [:get, :patch, :put, :delete, :post, :options, :head]
)
end
end
end
end
然后,我尝试搜索有关无效的真实性、令牌和http源文件头的内容,但是找不到有用的解决方案或我能理解的解决方案。
(最后注意:我尝试将它从post请求更改为get请求,但它成功了,但是post会导致错误)
谢谢你事先给我的建议
发布于 2021-01-13 11:50:22
我认为这是一个CSRF (跨站点请求伪造)问题。Rails试图防止向控制器发出无效请求。它正在您的请求头上寻找一个authenticity_token
,此令牌通过html.erb
表单中的一个隐藏元素进入请求,用于将请求发送到特定路径。当您使用rails作为API时,这些令牌是不存在的。
防止此异常的策略有多种,它们都有不同的安全含义。这里是一个很好的起点:Rails API设计而不禁用CSRF保护
发布于 2022-08-01 19:48:47
在我的例子中,问题在于虚拟主机的Ngixn设置。在以下网站找到答案:https://github.com/rails/rails/issues/22965#issuecomment-169956605
修正通过在Nginx中添加更多的头(X转发-Ssl on,X转发-端口443和X转发-主机名)
编辑后的部分如下:
location @app {
proxy_pass http://app;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header Host $http_host;
proxy_redirect off;
}
发布于 2022-09-09 21:37:39
https://stackoverflow.com/questions/65688157
复制相似问题