简体   繁体   English

我的 javascript 获取 API 调用有什么问题?

[英]What is wrong with my javascript fetch API call?

I have a javascript fetch API call made to a Django backend server我有一个 javascript fetch API 调用 Django 后端服务器

const res = fetch(url, {
  credentials: 'include',
  method: 'POST',
  mode: 'same-origin',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'X-CSRFToken': csrftoken
  },
  body: JSON.stringify(requestBody),
  })
  .then((response) => response.json())
  .then((responseJson) => {
    return responseJson.movies;
  })
  .catch((error) => {
    console.error(error);
  });

If I output the requestBody on the console before using it in the request, it looks like follows如果我 output 控制台上的 requestBody 在请求中使用它之前,它看起来如下

{"add-Choice":["L"],"add-Left":["1"],"add-Right":["1"],"add-Value":["100"],"add-match":["8"],"user":["siteuser1"],"csrfmiddlewaretoken":["3K89ZvofjhIL2nZQoCcxphjmXborujsaLPn2FzlYiVmiBLODWhQQiAB5BhSXkQcF"],"add":["Submit"]}

Here string "add-" is used as a form prefix on the Django side view post methode.此处字符串“add-”用作 Django 侧视图帖子方法的表单前缀。 However, on the server view side, if I print the request.POST as follow但是,在服务器视图方面,如果我按如下方式打印 request.POST

def post(self, request, *args, **kwargs):
    print('Post request: ', request.POST)

I get the output as an empty QueryDict as follow我得到 output 作为空 QueryDict 如下

Post request:  <QueryDict: {}>
Internal Server Error: /matchoffers/8

The request is being sent to the correct URL and is picked up the correct view-post methode.请求被发送到正确的 URL 并被拾取正确的视图发布方法。 But it fails because the request is empty.但它失败了,因为请求是空的。

If you're doing REST-based web service stuff... you should ignore request.POST.如果你正在做基于 REST 的 web 服务的东西......你应该忽略 request.POST。

 — Malcom Tredinnick, Django developers group

Just in case you are using DRF and you forgot to tell us以防万一您使用 DRF 而您忘记告诉我们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM