我有一个带有jwt身份验证的django-rest-framework api。该API可以正常工作并具有身份验证。我可以通过浏览器中的URL很好地使用api,但是尝试使用React访问api时会遇到麻烦。已经完成了许多教程,取得了不同程度的成功。
我正在尝试扩展React Frontend处的tut以使用我的api中的其他路由,但不确定如何?
在我的应用js中,我首先将待办事项列表添加到了我的状态:
constructor(props) {
super(props);
this.state = {
displayed_form: "",
logged_in: localStorage.getItem("token") ? true : false,
username: "",
todos: []
};
}
然后我在我的componentDidMount函数中添加了对getTodos方法的调用
componentDidMount() {
if (this.state.logged_in) {
axios
.post("http://localhost:8000/token-auth/", {
headers: {
authorization: `JWT ${localStorage.getItem("token")}`
}
})
.then(res => res.json())
.then(json => {
this.setState({ username: json.username });
})
.then(this.getTodos());
}
}
我需要某种getTodos函数:
getTodos = (e, data) => {
e.preventDefault();
fetch("http://localhost:8000/core/users/", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(json => {
localStorage.setItem("token", json.token);
this.setState({
logged_in: true,
displayed_form: "",
username: json.user.username
});
});
};
在后端,getTodos函数中的url应该是列出用户的URL,因为在django应用程序中,后端urls.py就是这样:
from django.urls import path
from .views import current_user, UserList
urlpatterns = [
path('current_user/', current_user),
path('users/', UserList.as_view())
]
因此url应该返回一个我可以迭代的json序列化程序?
我在return()中拥有这个:
{this.state.todos.map(item => (
<div key={item.id}>
<h2>{item.json.username}</h2>
</div>
))}
我在做什么错了?