【发布时间】:2020-12-14 21:14:11
【问题描述】:
我是网络开发的新手,我的第一个网站遇到了一些麻烦。我在 API 的后端使用 Django REST Framework,在前端使用 React.js。我在 URL 127.0.0.1:8000/course/1 上,我正在尝试调用 API 以检索课程 1 的信息。API 在 127.0.0.1:8000/api/courses/1 中,所以我使用:
fetch('localhost:8000/api/courses/1')
问题在于它显然在127.0.0.1:8000/course/1/127.0.0.1:8000/api/courses/1 上发出了一个显然不存在的GET 请求。问题在于,由于某种原因,它会自动将 fetch 的参数附加到当前 URL。我用fetch('api/course/1')从主页URL尝试了这个,它可以工作。我该怎么办?
这是完整的代码:
import React, { Component } from 'react';
export class Course extends Component {
constructor(props) {
super(props);
this.state = {
course: {}
}
this.getCookie = this.getCookie.bind(this);
this.fethCourse = this.fetchCourse.bind(this);
}
getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie != '') {
let cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
fetchCourse() {
fetch('localhost:8000/api/courses/1', {
method: 'GET',
headers: {
'X_CSRFToken': this.getCookie('csrftoken'),
'Accept': 'application/json',
'Content-type': 'application/json'
}
})
.then(response => response.json())
.then(data => this.setState({
course: data
}))
.catch(err => console.log(err))
}
UNSAFE_componentWillMount() {
this.fetchCourse();
}
render() {
const course = this.state.course;
return (
<div>
<h1>{course.name}</h1>
</div>
)
}
}
export default Course;
来自运行服务器的终端错误(manage.py):
"GET /static/frontend/main.js HTTP/1.1" 304 0
Not Found: /course/1/127.0.0.1:8000/api/courses/1
【问题讨论】:
-
您是否尝试过添加
http://前缀?
标签: javascript django reactjs django-rest-framework fetch