[Nuxt x Rails] Proxy settings due to CORS error

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.

Set up front-end proxy

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'
      }
    },
  },

Set up backend CORS

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

Extra edition: When managing sessions on the server side

config/application.rb


config.api_only = false

If you are using API mode, it is true, so check it

Recommended Posts

[Nuxt x Rails] Proxy settings due to CORS error
Nuxt.js x Rails app creation CORS policy Error resolution
[STS] Error due to project overlap
[Rails] About the error when displaying the screen due to the autofocus of the form
[Rails 5.x] How to introduce free fonts
The road to Japaneseizing Rails devise error messages
[Rails] How to solve "Uglifier :: Error: Unexpected character'`'"
Error deploying rails5 + Mysql to heroku with Docker-compose
[Rails] How to get success and error messages