Sometimes it is necessary to use fetch from a server secured with basic auth (very often in case of staging domains), usually, the authorization is done by login and password included within the URL itself:
user:[email protected]
JavaScript may seem pretty obvious:
const result = await fetch(`user:[email protected]/${endpoint}`, {
method: 'POST',
body: content,
headers: {
'Content-Type': 'application/json',
},
});
But in case of fetch
this is not allowed and will result in an error:
TypeError: Failed to execute 'fetch' on 'Window': Request cannot be constructed from a URL that includes credentials: https://user:[email protected]
To make it work, get rid of the login and password and add them to the fetch with:
const result = await fetch(`domain.com/${endpoint}`, {
method: 'POST',
body: content,
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${btoa('user:pass')}`,
},
});