使用凭据发送请求

时间:2019-05-26 10:31:41

标签: reactjs cors ruby-on-rails-5

我在Rails 5上制作了一个用ruby编写的身份验证api,并编写了一个javascript前端。通过接收电子邮件和密码,然后将cookie发送回浏览器来工作。但是,当我尝试发出请求时,控制台显示以下错误:

从原点“ http://localhost:3000/users/login”到“ http://localhost:3001”的XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:“访问控制”的值响应中的-Allow-Credentials标头为”,当请求的凭证模式为“ include”时,标头必须为“ true”。 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

1 个答案:

答案 0 :(得分:0)

我认为您应该使用机架cors。

  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”。

相关问题