我正在尝试从我的反应前端使用精细上传器,上传到我的rails 5后端。
rack-cors在我的中间件列表中排名第二:
use Webpacker::DevServerProxy
use Rack::Cors
use Rack::Sendfile
use ActionDispatch::Static
use ActionDispatch::Executor
use ActiveSupport::Cache::Strategy::LocalCache::Middleware
use Rack::Runtime
use ActionDispatch::RequestId
use ActionDispatch::RemoteIp
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use WebConsole::Middleware
use ActionDispatch::DebugExceptions
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActiveRecord::Migration::CheckPending
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
use Warden::Manager
run Project::Application.routes
当上传者试图上传图片时,我进入控制台:
Failed to load http://localhost:5000/item/1374/image: Response to preflight
request doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin 'http://lvh.me:3000' is
therefore not allowed access.
我可以看到预检(options
)http请求,其中包含以下数据:
GENERAL
Request URL:http://localhost:5000/item/1374/image
Request Method:OPTIONS
Status Code:200 OK
Remote Address:127.0.0.1:5000
Referrer Policy:no-referrer-when-downgrade
RESPONSE HEADERS:
HTTP/1.1 200 OK
Content-Type: text/plain
Transfer-Encoding: chunked
REQUEST HEADERS:
OPTIONS /item/1374/image HTTP/1.1
Host: localhost:5000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: update
Origin: http://lvh.me:3000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36
Access-Control-Request-Headers: cache-control,x-requested-with
Accept: */*
DNT: 1
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,it;q=0.8
这是同一个电话的cors调试日志:
{"Access-Control-Allow-Origin"=>"http://lvh.me:3000", "Access-Control-Allow-Methods"=>"GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD", "Access-Control-Expose-Headers"=>"access-token, expiry, token-type, uid, client, Access-Control-Allow-Origin", "Access-Control-Max-Age"=>"1728000", "Access-Control-Allow-Credentials"=>"true"}
Incoming Headers:
Origin: http://lvh.me:3000
Access-Control-Request-Method: update
Access-Control-Request-Headers: cache-control,x-requested-with
Preflight Headers:
Content-Type: text/plain
我的config/initializers/cors.rb
看起来像:
Rails.application.config.middleware.insert_before 0, Rack::Cors, debug: true, logger: (-> { Rails.logger }) do
allow do
origins 'localhost:3000',
'http://localhost:3000',
'127.0.0.1:3000',
/\Ahttp:\/\/192\.168\.0\.\d{1,3}(:\d+)?\z/,
'http://lvh.me:3000'
resource '*',
headers: :any,
expose: %w[access-token expiry token-type uid client Access-Control-Allow-Origin],
credentials: true,
methods: %i[get post put patch delete options head]
end
end
我也尝试使用origin '*'
和credentials: false
,但得到的结果相同。
我不明白问题出在哪里..
答案 0 :(得分:2)
我的错,我正在申请update
,但只允许put
和patch
。
我将请求更改为put,现在我离walhalla更近了一步。