When I submit a form of user information to Rails from the front side, I get this error.
Access to XMLHttpRequest at 'http://localhost:3000' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Usually, the front and back domains have the same URL, but they can be different. At that time, the error "Do not allow cross-domain communication" occurs.
Therefore, it is necessary to eliminate the CORS error by setting the proxy settings on both the Nuxt side and Rails side.
For About CORS, please refer to the link.
The local server on the back side is http: // localhost: 3000
.
$ yarn add @nuxtjs/proxy
nuxt.config.js
modules: [
'@nuxtjs/proxy',
],
proxy: {
'/api': {
target: 'http://localhost:3000',
pathRewrite: {
'^/api': '/api'
}
},
},
The local server on the front side is http: // localhost: 8080
.
Gemfile
gem 'rack-cors'
$ bundle install
config/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
#Domains allowed
origins 'localhost:8080'
#Allowed headers and methods
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
config/application.rb
config.api_only = false
If you are using API mode, it is true, so check it
Recommended Posts