reactjs - 使用凭据发送请求
问题描述
我在 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
解决方案
我认为你应该使用齿条。
在您的 Rails 应用程序 Gemfile 中添加 gem 'rack-cors'
gem 'rack-cors'
将以下代码添加到 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”。
推荐阅读
- azure-devops - 如何使用 Azure Devops 中的 Azure Devops API 在 C# 中创建/更新具有父子关系的工作项
- java - Liferay 中用于访问邮件的服务器错误
- c# - 将子类与父类列表区分开来
- python-3.x - 在 tkinter 窗口中显示标签后,我无法弄清楚如何重置标签
- excel - 我正在寻找一个代码,它在 A 列的值为 x 的行中选择指定范围
- c# - 检查两个对象之间是否所有属性(除了两个)是否匹配的干净方法?
- reactjs - 在 React JS 中将 props / state 传回父组件
- angularjs - 在更改 ng-model 值时应该更改
- sql-server - 如何通过给出函数名称,特定字母,下一个字母来使用sql server中的函数在一个特定字母之后选择下n个字母
- odoo - 如何在没有付款的情况下查找 ReportsInvoices 的外部 ID