Javascript 使用React.js使用auth令牌调用REST API
这是一个调用RESTAPI的尝试,它作为身份验证令牌,使用React.js。我正在以Javascript 使用React.js使用auth令牌调用REST API,javascript,reactjs,rest,api,react-native,Javascript,Reactjs,Rest,Api,React Native,这是一个调用RESTAPI的尝试,它作为身份验证令牌,使用React.js。我正在以POST的形式发送令牌请求,它被解读为GET,有人能帮我吗 componentDidMount() { fetch("theURL/api-token-auth/", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", ema
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));
}
您正确地使用了方法
POST
,因此这不是问题。但是,要发送的数据应该在正文中,而不是标题中
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));
}
您正确地给出了方法POST
,因此错误可能在后端。但是,要发送的数据可能应该在正文中,而不是在标题中。尝试body:JSON.stringify({email:email,password:password})
在body中没有发送数据的情况下发布帖子是没有意义的。它现在正在工作,但现在我如何存储令牌的值以进行另一次获取@你能给我们看看后端吗?你的想法似乎是对的。下面是我们在我的公司使用fetch的方式,带有一个Auth代码:fetch(路由,{method:'POST',头:{Content-Type':'application/json',Auth:AUTHCODE},body:json.stringify({data})}
AUTHCODE应该只用于确认用户是来找一个好位置的。您应该将正文用于所有其他数据。