I have established an API connection which retrieves hundreds of objects and their values via JSON. One of these is a web path to a text only html page. This object is called 'WebVersionTextURL' (the object I am having trouble manipulating).
I am using this in a function to retrieve the text only html, and add this to the JSON output.
The issue that I am running into is that the web path returned is http and the request needs to be served over https. I have tested the text only URL by adding https instead of http to see if I could still access the page, and the response loads fine - which is great.
I am trying to use .replace to substitute http:// for https:// but for whatever reason, I am unable to get it to replace.
CODE:
<button id="go" class="btn">TEST</button>
<p>Check console for result</p>
<script>
const logBtn = document.getElementById('go');
logBtn.addEventListener('click', fetchData);
function getText(URL){
var request = new XMLHttpRequest();
request.open('GET', URL, true);
request.send(null);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
var type = request.getResponseHeader('Content-Type');
if (type.indexOf("text") !== 1) {
return request.responseText;
}
}
}
}
async function fetchData() {
const response = await fetch('url_to_api_connection_here');
const data = await response.json();
data.forEach(obj => {
Object.entries(obj).forEach(([key, value]) => {
// Log everything to console
console.log(`${key} ${value}`);
// Log just WebVersionTextURL and contents
if (key == "WebVersionTextURL") {
value.replace("http://", "https://");
// console.log(`${key} ${value}`);
console.log(getText(`${value}`));
}
});
console.log('-------------------');
});
}
</script>
Sample of JSON data returned from API: NB - I have changed the information to sample data
[{
"Name":"John Citizen",
"Subject":"This is a test only",
"WebVersionTextURL":"http://linktowebpagetextonlyhere/t"
}]
Sample of the response data:
Name John Citizen
Subject This is a test only
WebVersionTextURL http://linktowebpagetextonlyhere/t
undefined
-------------------
Error message in console:
Mixed Content: The page at 'https://linktolandingpage' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://linktowebpagetextonlyhere/t'. This request has been blocked; the content must be served over HTTPS.
Thank you