我看到了很多类似的问题,但是这些问题对我没有用。我真的不知道为什么我无法访问api。我已经用邮递员中的令牌测试了它,并返回了正确的数据。你能纠正我吗?
后端
# model
class Department(models.Model):
name = models.CharField(max_length=100
# viewset
class DepartmentViewSet(viewsets.ModelViewSet):
queryset = models.Department.objects.all()
serializer_class = serializers.DepartmentSerializer
permission_classes = (IsAdminUser,)
#setting.py
CORS_ALLOWED_ORIGINS = [
"http://localhost:8080",
"http://127.0.0.1:8080",
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
}
前端
# axios-base.js
import axios from "axios";
const getAPI = axios.create({
baseURL: 'http://127.0.0.1:8000',
timeout: 1000,
})
export {getAPI}
#template.vue
<script>
import { getAPI } from "../../src/axios-base.js";
export default {
name: "Department",
data() {
return {
departments: [],
};
},
mounted() {
this.getAllDepartment();
},
methods: {
getAllDepartment: function() {
const token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl9....."; <- access token
getAPI.get("/attendance-rest-api/departments/",
{
email: "admin@gmail.com", <- admin account
password: "admin",
},
{
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
}
)
.then((res) => {
this.departments = res.data;
})
.catch((err) => {
console.log(err);
});
},
},
};
</script>
我的api json视图
{
"url": "http://localhost:8000/attendance-rest-api/departments/1/",
"id": 1,
"name": "GIC"
},
{
"url": "http://localhost:8000/attendance-rest-api/departments/2/",
"id": 2,
"name": "GEE"
},
我在Django终端出现错误
Unauthorized: /attendance-rest-api/departments/
[20/Sep/2020 13:18:04] "GET /attendance-rest-api/departments/ HTTP/1.1" 401 58
我在浏览器中遇到的错误
detail: "Authentication credentials were not provided."
答案 0 :(得分:1)
您正在滥用Axios API。在GET请求中,应仅将一个参数-config
对象传递到相应的方法中,并将参数传递到该对象的params
属性内。像这样:
getAPI.get("/attendance-rest-api/departments/",
{
params: {
email: "admin@gmail.com", <- admin account
password: "admin",
},
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
}
)
使用现有代码,该第二个对象(包含标头)将被忽略,从而导致您看到错误。
作为旁注,我真的不确定为什么在这里使用GET。通常,将密码作为GET的参数不仅是一个(非常)不好的主意;但是,在这种情况下,甚至还不清楚目的是什么。
我怀疑您只是结合了一些POST请求中的代码(也许用于登录方案?)。但是,GET和POST确实是不同的野兽。