Django Rest APi身份验证凭据



我正在做一个使用Django作为后台服务器和flutter作为前端框架的项目,今天当我试图使用REST API将数据从flutter UI应用程序POST到Django服务器数据库时,我遇到了一个问题;细节":"未提供身份验证凭据"问题是,当我从web浏览器发出POST请求时,它运行良好。我想我需要从flutter应用程序向Django服务器提供更多信息来进行身份验证,然后我可以在这里POST数据,这是flutter方法

Future<CreateProduct> submitProduct(String name , String price , String brand , String countinstock , String category , String description) async {
String createProductUri = "http://127.0.0.1:8000/api/products/create/";
final response = await http.post(Uri.parse(createProductUri),body: {
"name": name,
"price": price,
"brand": brand,
"countInStock": countinstock,
"category": category,
"description": description
});
if (response.statusCode == 201){
final responseString = response.body;
return createProductFromJson(responseString);
}
}

Django请求

@api_view(['POST'])
@permission_classes([IsAdminUser])
def createProduct(request):
user = request.user
data = request.data
product = Product.objects.create(
user=user,
name=data['name'],
price=data['price'],
brand=data['brand'],
countInStock=data['countInStock'],
category=data['category'],
description=data['description'],
)
serializer = ProductSerializer(product, many=False)
return Response(serializer.data)

试试这个:

final response = await http.post(Uri.parse(createProductUri),
headers:{"Accept": "application/json",
'Content-Type': 'application/json'},
body: {
"name": name,
"price": price,
"brand": brand,
"countInStock": countinstock,
"category": category,
"description": description
});

使用此

headers: {
"Authorization": 'Bearer token'
}

解决了问题

最新更新