Kir*_*ole 2 javascript django fetch django-rest-framework reactjs
我是网络开发新手,我的第一个网站遇到了一些麻烦。我在后端使用 Django REST Framework 作为 API,在前端使用 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')
Run Code Online (Sandbox Code Playgroud)
问题是它显然发出了一个127.0.0.1:8000/course/1/127.0.0.1:8000/api/courses/1显然不存在的 GET 请求。问题是,由于某种原因,它会自动将 的参数附加fetch到当前 URL。我从主页 URL 尝试了这个,fetch('api/course/1')它有效。我应该怎么办?
这是完整的代码:
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;
Run Code Online (Sandbox Code Playgroud)
运行服务器(manage.py)的终端出现错误:
"GET /static/frontend/main.js HTTP/1.1" 304 0
Not Found: /course/1/127.0.0.1:8000/api/courses/1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1280 次 |
| 最近记录: |