Axios 添加 withCredentials = true 出现跨域问题,如何解决?

546 阅读1分钟

前端项目使用 Vue,在项目中使用 Axios 请求接口时,Axios 使用了 withCredentials

axios.defaults.withCredentials = true

部署后,请求出现跨域问题。

后端项目使用 Rails,使用 gem 'rack-cors' 来实现跨域,但是 credentials 的默认配置是 false,应该改为 true。

并且此时,origin 不能写成 *,应该写成前端的域名。

  • credentials (boolean, default: false): Sets the Access-Control-Allow-Credentials response header. Note:  If a wildcard (*) origin is specified, this option cannot be set to true. Read this security article for more information.

后端配置 cors 具体代码:

# config/initializers/cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'test.com'
    resource '*', headers: :any, methods: [:get, :post, :patch, :put], credentials: true
  end
end