简体   繁体   English

使用 JS Fetch 模拟 Python HTTP 请求

[英]Emulate Python HTTP request using JS Fetch

I can successfully do a simple HTTP request using python requests:我可以使用 python 请求成功执行简单的 HTTP 请求:

def renew_token():
    """
    Send a request to renew the login token
    """
    url = url
    fields = {
        "username": "username",
        "password": "password"
        }
    r = requests.post(url, data=fields)
    print(r)

I am trying to do the exact same request using javascript fetch, but with no luck.我正在尝试使用 javascript fetch 执行完全相同的请求,但没有成功。

async function renewToken(url = '', fields = {}) {
    const response = await fetch(url, {
      method: 'POST'
      data: JSON.stringify(fields),
      mode: 'cors',
      cache: 'no-cache', 
      headers: {
        'Content-Type': 'application/json',
        //'Content-Type': 'application/x-www-form-urlencoded',
      },
    });
    return await response.json();
  }

  renewToken('url', { username: 'username', password: 'password' })
  .then((data) => {
  console.log(data); // JSON data parsed by `response.json()` call
  });

The error I get back is:我得到的错误是:

{ data: null,
  message: 'No username or password provided',
  status: 'api-error' }

which implies there is something wrong with the content type.这意味着内容类型有问题。 I've tried changing the content-type to 'application/x-www-form-urlencoded', but I get the same error.我尝试将content-type更改为“application/x-www-form-urlencoded”,但我遇到了同样的错误。

What am I missing to emulate the python request using fetch?使用 fetch 模拟 python 请求时我缺少什么?

Had to use form data, not sent data in body:必须使用表单数据,而不是在正文中发送数据:

async function renewToken(url = '', fields = {}) {
            const response = await fetch(url, {
              method: 'POST', //
              body: 'username=username&password=password',
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
              },
            });
            return await response.json(); 
          }

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

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