{detail: "Authentication credentials were not provided." } on get request with simplejwt



我看到了很多类似的问题,但这些问题对我不起作用。我真的不知道为什么我不能访问api。我已经用poster中的令牌测试了它,它返回了正确的数据。你能纠正我吗。

后端

# 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."

您正在滥用Axios API。在GET请求中,只有一个参数-config对象-应该传递到相应的方法中,并且params应该在该对象的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确实是不同的野兽。

最新更新