[英]Emulate Python HTTP request using JS Fetch
我可以使用 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)
我正在尝试使用 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
});
我得到的错误是:
{ data: null,
message: 'No username or password provided',
status: 'api-error' }
这意味着内容类型有问题。 我尝试将content-type
更改为“application/x-www-form-urlencoded”,但我遇到了同样的错误。
使用 fetch 模拟 python 请求时我缺少什么?
必须使用表单数据,而不是在正文中发送数据:
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.