I can successfully do a simple HTTP request using python requests:
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.
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.
What am I missing to emulate the python request using fetch?
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.