I'm facing some issues while trying to fetch a response from a URL without an endpoint. Despite using the Fetch API to send HTTP requests, I keep getting a null value in return.
The use of mode: "no-cors"
results in an opaque response that cannot be accessed with JavaScript.
According to this resource, receiving a null value is expected in such cases.
If a website includes the Access-Control-Allow-Origin
header in its responses, frontend JavaScript code can access those responses directly.
However, the site (Google) you are attempting to reach does not include this header.
Is there a solution to this issue within pure JS?
You can access responses from websites that permit it or configure your backend to include the Access-Control-Allow-Origin
header.
For example, the following code snippet functions correctly:
async function testResponse() {
let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
let json = await response.json()
console.log(json)
}
testResponse()
If you need to access data from a site that restricts it, utilizing a CORS proxy
may provide a workaround.
Further details can be found in this explanation.
Additionally, fetch
utilizes a promise-based API. This allows you to interact with it as follows:
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()
You do not need to utilize both methods simultaneously.