【发布时间】:2022-01-19 14:44:13
【问题描述】:
我已设法编写代码,将客户从我的 Angular 服务方法添加到我的 MongoDB 集合到我的 Django http 函数,如下所示:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json'
}),
withCredentials: false
}
@Injectable()
export class MongoService {
myApiBaseUrl = "http://localhost:8000/mydjangobaselink/";
constructor(private httpClient: HttpClient) { }
addCustomer(customerFormInfo: Customer): Observable<Customer> {
return this.httpClient.post<Customer>(`${this.myApiBaseUrl}`, JSON.stringify(customerData), httpOptions);
}
deleteCustomer(): Observable<Customer> {
return this.httpClient.delete<Customer>(`${this.myApiBaseUrl}`);
}
}
@csrf_exempt
@api_view(['GET', 'POST', 'DELETE'])
def handle_customer(request):
if request.method == 'POST':
try:
customer_data = JSONParser().parse(request)
customer_serializer = CustomerModelSerializer(data=customer_data)
if customer_serializer.is_valid():
customer_serializer.save()
# Write customer data to MongoDB.
collection_name.insert_one(customer_serializer.data)
response = {
'message': "Successfully uploaded a customer with id = %d" % customer_serializer.data.get('id'),
'customers': [customer_serializer.data],
'error': ""
}
return JsonResponse(response, status=status.HTTP_201_CREATED)
else:
error = {
'message': "Can not upload successfully!",
'customers': "[]",
'error': customer_serializer.errors
}
return JsonResponse(error, status=status.HTTP_400_BAD_REQUEST)
except:
exceptionError = {
'message': "Can not upload successfully!",
'customers': "[]",
'error': "Having an exception!"
}
return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
elif request.method == 'DELETE':
try:
CustomerModel.objects.all().delete()
# Delete customer data from MongoDB.
collection_name.deleteMany({})
return HttpResponse(status=status.HTTP_204_NO_CONTENT)
except:
exceptionError = {
'message': "Can not delete successfully!",
'customers': "[]",
'error': "Having an exception!"
}
return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
POST 方法工作正常,我可以在我的 MongoDB Compass 中看到添加的文档,但是当我尝试删除时,我得到:
删除 http://localhost:8000/mydjangobaselink/500(内部服务器错误)
我看到的所有帖子和文章都解决了浏览器、本地主机等中的通信问题……但鉴于我的发布方法运行良好,我认为这不是我的问题。另外,在 Postman 中,我得到 无法成功删除!
谁能看到我无法从数据库中删除的问题?
【问题讨论】:
标签: django angular mongodb http django-rest-framework