reactjs - 授权问题:Axios POST 中的 Bearer access_token(标头)反应
问题描述
我正在尝试从使用授权和承载 access_token 的端点创建登录。我不知道将令牌正确传递给标头中的授权,因此会发生以下错误。
响应 {type: "basic", url: " http://127.0.0.1:8000/ ", 重定向: true, status: 200, ok: true, ...}
我试图阅读 Axios 帖子和授权类型,以了解如何将 access_token 传递给承载。问题是令牌是在每个用户注册期间生成的。如何在登录中使用它。图片来自邮递员来说明。我将注册时生成的 access_token 复制到授权中。
handleLogin(event){
event.preventDefault();
var formData = new FormData();
formData.append("password", this.state.l_password);
formData.append("email",this.state.l_email);
formData.append("remember_me", true);
fetch('api/auth/login',
{
headers:{
// 'accept': 'application/x-www-form-urlencoded',
'content-type': 'application/json',
'authorization': 'bearer',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: "POST",
body:formData
}
)
.then(response => {
console.log(response);
})
.then(json => {
return json.json();
})
}
在 Postman 中,我只使用 content-type: application/json 作为登录头。但最令人困惑的是,它显示状态:好的,它实际上并没有工作。
解决方案
你做的有点不对。首先,您必须考虑 API 使用需要在端点中指定的令牌,例如/oauth/token。首先,如果您有邮递员,请尝试测试http://localhost:port/oauth/token然后指定标头 content-type:application/json 并在您的正文中执行以下操作:-
{
"username": "something@yahoo.com",
"password" : "abcdef",
"client_id": "4",
"client_secret" :"XXXXXXXXXXXXXXXXXXXXXX",
"grant_type": "password",
"scope": "*"
}
如果您仔细查看下面的代码,您可以看到我将所有内容都放入了正文中。
但是,我已经重写了您的代码
handleLogin(event){
event.preventDefault();
fetch('/oauth/token',
{
method: "POST",
headers:{
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body:`grant_type=password&username=${this.state.username}&password=${this.state.l_password}&client_id=4&client_secret=XXXXXXXXXXXXXXXXXXX&scope=*`
}
)
.then(response =>
response.json()
)
.then(responseJson => {
const returnObj = responseJson;
console.log(returnObj);
})
要阅读更多信息,请在此处输入链接描述, 其他资源请在此处输入链接描述
推荐阅读
- facebook - 如何从 Facebook 机器人中删除“开始”按钮
- ios - 如何将用户在应用程序中拍摄的图像保存到 UIImages 数组中?斯威夫特 4
- java - 将网格从文件读取到 Java 中的特定类
- javascript - 在浏览器当前窗口滚动条中同时使用多种颜色
- c++ - 析构函数总是命中 Null
- python - PyQt5:来自 QTableWidget 的复选框中的状态更改
- ethereum - 将 GethNode 连接到外部 GethNode 失败
- google-cloud-platform - 加载操作中的 BigQuery 错误:总叶字段过多
- python - Pandas 将带有表格数据的整个文本文件加载到一列中
- julia - 如何获取 Julia 变量的类型?