【问题标题】:415 UNSUPPORTED MEDIA - API Post Javascript - Django415 不支持的媒体 - API Post Javascript - Django
【发布时间】:2021-04-18 07:08:05
【问题描述】:

我正在尝试在我的 Django 服务器上创建一个 API,但我正在努力创建一个由 Javascript 调用的 post 方法。

这是我的 API 视图

类componentFrameAPI(APIView):

def get(self, request):
    componentAPI = component.objects.all()
    serializer = componentSerializer(componentAPI, many=True)
    return Response(serializer.data)

def post(self):
    serializer = componentSerializer(componentAPI, data=self.data)
    if serializer.is_valid():
        # serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

这是我对 Javascript 的发帖请求。

let data = {componentName:"PostTest",componentBody:"TEST"}
datax = JSON.stringify(data)

var xhttp = new XMLHttpRequest()
xhttp.open("POST","http://127.0.0.1:8000/myurl/", true)
xhttp.setRequestHeader('X-CSRFToken', csrftoken)
xhttp.setRequestHeader('contentType', 'application/json')    
xhttp.send(datax)

我继续收到 415 错误,我真的不知道自己做错了什么。

注意:GET 方法可以正常工作。

感谢您的帮助。

贾科莫

【问题讨论】:

  • 我不确定 Django,但是在请求休息端点时您需要验证的几件事确保“contentType”、“应用程序/json”在请求和休息端点中也相同跨度>

标签: javascript python django ajax django-rest-framework


【解决方案1】:

您很接近,但xhttp.setRequestHeader('contentType', 'application/json') 中有错字

改成

xhttp.setRequestHeader('Content-Type', 'application/json')    

你应该没事 完整示例

let data = {componentName:"PostTest",componentBody:"TEST"}
datax = JSON.stringify(data)

var xhttp = new XMLHttpRequest()
xhttp.open("POST","http://127.0.0.1:8000/myurl/", true)
xhttp.setRequestHeader('X-CSRFToken', csrftoken)
xhttp.setRequestHeader('Content-Type', 'application/json')    
xhttp.send(datax)

【讨论】:

    猜你喜欢
    • 2016-11-26
    • 2015-06-02
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2022-01-17
    • 2020-09-03
    • 2017-03-06
    • 1970-01-01
    相关资源
    最近更新 更多