繁体   English   中英

当凭证包括

[英]CORS policy Access-Control-Allow-Origin header in the response mustn't be wildcard * when credentials include

I am a junior dev and this is my first time deploying a Rails API and React-Redux front-end APPs both on Heroku, My backend has users authentications using session cookies and my frontend is sending requests with credentials: "include" which doesn't pass CORS 政策。 我尝试了很多教程,但没有一个修复了我的错误。 这是错误和代码

错误

Access to fetch at 'https://lets-kari-to-the-next.herokuapp.com/api/v1/session/status' from origin 'https://lets-meetup-app.herokuapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

配置.ru

 use Rack::Cors do
 allow do
   origins '*'
   resource '*',
       :headers => :any,
       :methods => [:get, :post, :delete, :put, :patch, :options]
 end
end

React-Redux 获取方法

 import { LOGGED_IN, LOGGED_OUT, BASE_URL } from "./types" export const sessionStatus = () => { return dispatch => { return fetch(`${BASE_URL}/api/v1/session/status`, { headers: { "Content-Type": "application/json", "Accept": "application/json", "Allow-Control-Allow-Origin": 'https://lets-meetup-app.herokuapp.com', "Access-Control-Allow-Credentials": "true" }, credentials: "include", }).then(resp => resp.json()).then(data => { data.logged_in? dispatch({ type: LOGGED_IN, user: data.user.data.attributes, interests: data.interests }): dispatch({ type: LOGGED_OUT, payload: data }) }) } }

在您的 gem 文件中添加gem 'rack-cors'bundle install

在您的application.rb中添加以下代码段

config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', 
          headers: :any, 
          expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'],
          methods: [:get, :post, :options, :delete, :put]
      end
    end

config.ru添加credentials: true并在origins中指定域地址解决了这个问题

 use Rack::Cors do allow do origins 'https://lets-meetup-app.herokuapp.com' resource '*', :headers =>:any, :methods => [:get, :post, :delete, :put, :patch, :options], credentials: true end end

 import { LOGGED_IN, LOGGED_OUT, BASE_URL } from "./types" export const sessionStatus = () => { return dispatch => { return fetch(`${BASE_URL}/api/v1/session/status`, { headers: { "Content-Type": "application/json", "Accept": "application/json" }, credentials: "include", }).then(resp => resp.json()).then(data => { data.logged_in? dispatch({ type: LOGGED_IN, user: data.user.data.attributes, interests: data.interests }): dispatch({ type: LOGGED_OUT, payload: data }) }) } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM