在 javascript 中请求(来自 python)

Request in javascript (from python)

我试图在 javascript 中创建一个请求,之前使用 python 时效果很好。

以下是我用来 post python 请求的代码的准确表示:


url = 'https://website.com/api/e1'
    
header = {
   'authorization': 'abcd1234'
}
payload = {
    'content': "text",
}
r = requests.post(url, data=payload,headers=header )

这个(以上)在 python.

中工作得很好

现在我在 javascript 中所做的如下:

payload = {
    "content": "this is text",
  };
  fetch("https://website.com/api/e1", {
    method: "POST",
    headers: {
      "authorization":
        "abcd1234",
    },
    body: JSON.stringify(payload),
  });

但这会返回 错误 400- Bad request

你不需要这样做 body: JSON.stringify(payload), 而是你可以像这样简单地在正文中传递有效负载 body:payload

在pythonrequests.post上使用数据参数时,默认的Content-Typeapplication/x-www-form-urlencoded(我在文档上找不到,但是我查了下request . 知道的欢迎留言评论)。

要获得与 fetch 相同的结果,您必须执行以下操作。

const payload = {
  'content': 'this is text',
};
fetch('https://website.com/api/e1', {
  method: 'POST',
  headers: {
    'authorization': 'abcd1234',
  },
  body: new URLSearchParams(payload),
});