I want to get a response(HTML) from a URL with no endpoint. So I sent HTTP requests using the Fetch API, but it continues to return a null value.
By using, mode: "no-cors"
you get an opaque response and that can't be accessed with JavaScript.
So, as stated here, you should get a null value.
If a site, sends the Access-Control-Allow-Origin
header in its responses, only then frontend JavaScript code can directly access responses from that site.
And, the site (google) you are trying to access does not send that.
Is there a way to solve this problem in the pure JS environment?
You can access responses from sites that allow it or configure your backend to send the Access-Control-Allow-Origin
header.
For example this snippet works,
async function testResponse() {
let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
let json = await response.json()
console.log(json)
}
testResponse()
However, if you want to access response from a site that does not allow it, CORS proxy
might help.
Details available in this answer.
Also, fetch
uses promised-based API. That means you can use it like this,
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then( response => console.log(response) )
or,
async function test() {
let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
console.log(response)
}
test()
No need to use both at the same time.