首页 > 解决方案 > 使用凭据发送请求

问题描述

我在 rails 5 上用 ruby​​ 制作了一个身份验证 api,以及一个 react js 前端。它的工作原理是获取电子邮件和密码,然后将 cookie 发送回浏览器。但是,当我尝试发出请求时,控制台显示以下错误:

从源“ http://localhost:3001 ”访问“ http://localhost:3000/users/login ”处的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:值响应中的“Access-Control-Allow-Credentials”标头为“”,当请求的凭据模式为“包含”时,该标头必须为“真”。XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

    #react component - signin.js

    axios(
        `http://localhost:3000/users/login`, {
        method: "post",
        withCredentials: true,        
        data: {email: this.state.email, password: this.state.password}
        })
    .then(response => {
        console.log(response)
    })
    .catch(error => console.log(error))

}

      #rails login function
           def login
          #fetch user
           user = User.find_by(email: params[:email].to_s.downcase)
            #authenticate method
              if user && user.authenticate(params[:password])
        #disallow unconfirmed emails
        if user.confirmed_at?
            auth_token = JsonWebToken.encode({user_id: user.id})
            ##
            cookies.signed[:jwt] = {value:  auth_token, httponly: true}

            render json: {auth_token: auth_token, email:user.email}, 
              status: :ok


          else
            render json: {error: 'Email not verified' }, status: 
             :unauthorized
        end
    else
      render json: {error: 'Invalid username / password'}, status: 
            :unauthorized
    end
  end

标签: reactjscorsruby-on-rails-5

解决方案


我认为你应该使用齿条。

  1. 在您的 Rails 应用程序 Gemfile 中添加 gem 'rack-cors'

    gem 'rack-cors'

  2. 将以下代码添加到 config/application.rb

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

您可以提供源端点或使用“*”来允许所有,而不是源中的“example.com”。


推荐阅读