javascript - 使用 React.js 使用身份验证令牌调用 REST API
问题描述
这是尝试使用React.js调用作为身份验证令牌的REST API。我正在发送令牌请求,并且它已被读取为,有人可以帮助我吗?POST
GET
componentDidMount() {
fetch("theURL/api-token-auth/", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
email: "EMAIL",
password: "PASSWORD"
}
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
})
.then(json => {
this.setState({
isLoaded: true,
token: json
});
})
.catch(error => console.error(error));
}
解决方案
您正确使用了 method POST
,所以这不是问题。但是,您要发送的数据应该在body
而不是在headers
.
componentDidMount() {
const email = "test@example.com";
const password = "foobar";
fetch("theURL/api-token-auth/", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
email,
password
})
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
})
.then(json => {
this.setState({
isLoaded: true,
token: json
});
})
.catch(error => console.error(error));
}
推荐阅读
- python - 将锯齿状边缘近似为线
- python - 在 Python 中将列表转换为小写
- php - 关系数据库 - 在下拉列表中发送 id 值
- sql - SQL:查询以检索数据
- c# - 在 Visual Studio 2019 (C#) 中找不到 MqttMsgSubscribe.cs 错误
- r - 计算具有相同名称的多个条目的平均值
- python-3.x - Python - 烧瓶 API 映像
- python - 在 colab 中找不到 kaggle.json?
- haskell - QuickCheck:为什么没有通过测试的功能以及改用什么功能?
- angular - 'routerLink' 和 'fragment' 指令的绑定不起作用