最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

django rest framework - POST working with Postman but not via fetch in JavaScript - Stack Overflow

programmeradmin1浏览0评论

The post request to the Django Rest API framework works via Postman when the appropriate parameters are filled in the 'body' section. But the same does not work with the following JavaScript code:

var data = {emp_id:50,emp_name:'test',password:'pass123'};   
fetch('http://127.0.0.1:8000/signup/',{
    method:"POST",
    body: JSON.stringify(data),
    mode:"no-cors",
     headers: {
                "Content-Type": "application/json",
                // "Content-Type": "application/x-www-form-urlencoded",
            },
    })
    .then(response => response.json());

The following is the def that handles the POST request in the views.py of the REST-API:

@api_view(['GET', 'POST', ])
def signup(request):
    serializer = employeeSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

I'm new to this, can anyone tell me why the JavaScript code won't work?

EDIT: The error which the browser console shows is:

POST http://127.0.0.1:8000/signup/ 415 (Unsupported Media Type)

The post request to the Django Rest API framework works via Postman when the appropriate parameters are filled in the 'body' section. But the same does not work with the following JavaScript code:

var data = {emp_id:50,emp_name:'test',password:'pass123'};   
fetch('http://127.0.0.1:8000/signup/',{
    method:"POST",
    body: JSON.stringify(data),
    mode:"no-cors",
     headers: {
                "Content-Type": "application/json",
                // "Content-Type": "application/x-www-form-urlencoded",
            },
    })
    .then(response => response.json());

The following is the def that handles the POST request in the views.py of the REST-API:

@api_view(['GET', 'POST', ])
def signup(request):
    serializer = employeeSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

I'm new to this, can anyone tell me why the JavaScript code won't work?

EDIT: The error which the browser console shows is:

POST http://127.0.0.1:8000/signup/ 415 (Unsupported Media Type)
Share Improve this question edited Feb 22, 2019 at 12:26 Aseem Kannal asked Feb 22, 2019 at 12:17 Aseem KannalAseem Kannal 931 gold badge1 silver badge9 bronze badges 4
  • what is the result? what error message do you see in Developer Tools if any? – skyboyer Commented Feb 22, 2019 at 12:19
  • 1 do you not need another .then call in order to do something with the JSON response? – Robin Zigmond Commented Feb 22, 2019 at 12:20
  • 1 “can anyone tell me why the JavaScript code won't work?” - your browser console most likely can, so go check there. It is likely to point out that you have a CORS issues, so go read up on that keyword then if it is news to you. – 04FS Commented Feb 22, 2019 at 12:20
  • @skyboyer, there is an error message: 415 (Unsupported Media Type) – Aseem Kannal Commented Feb 22, 2019 at 12:38
Add a comment  | 

3 Answers 3

Reset to default 5

The issue is that by using no-cors mode you constrain yourself to using simple requests, which in turn cannot have content-type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain. In fact, if you look at the headers sent by the browser with your request, you'll see that the content type changes from application/json to text/plain - hence the error.

To fix your issue: remove no-cors mode and add cors headers to responses in your django app. You can use django-cors-headers for that.

Also, you have no issues with postman because it does not care about same-origin policy.

Try change headers to

headers: { 
    'Accept': 'application/json',
    'Content-Type': 'application/json' 
}

The accept header is used by to determine what format to sent the data back to the client in the response, guess it might be needed

I found the solution here : https://learning.postman.com/docs/sending-requests/generate-code-snippets/#generating-code-snippets-in-postman

with postman you can see the code of headers sent on the request on many languages (Node Axios, javascript fetch ...), then just copy paste the headers and all the data sent by postman to your app

发布评论

评论列表(0)

  1. 暂无评论