What is a way to receive a reply in JavaScript without using an endpoint?

Take a look at this code snippet I wrote:

...
    await fetch('https://example.com', {
      method: "GET",
      mode: "no-cors"
    })
    .then((response) => {
      console.log(response.body);
      console.log(response.status);
      return response.text();
    })
    .then((responseText) => {
      console.log(responseText);
    })
    .catch((error) => {
      console.log(error.toString());
    });
...

https://example.com (Yes)
https://example.com/test (No)

I need to receive an HTML response from a URL without any specific endpoint. Despite using the Fetch API to send HTTP requests, it keeps returning null.

Are there any solutions to this issue within a pure JavaScript environment?

Answer №1

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular-UI keypress event allows users to interact with components and

I am facing challenges while using the keypress feature in the following code snippet- <div ng-controller="GBNController"> ... <input id="search-field" type="text" placeholder="JSON Query" ng-model="queryText" ui-keypress="{enter: foo()}"/> .. ...

Swap out AJAX following a successful retrieval and when managing errors

I currently have a basic AJAX load function set up to load a specific URL: <div id="load"> <h1 id="status">Loading...</h1> </div> <script type="text/javascript"> $(document).ready(function(){ $.ajaxSetup({cache: false}); var ...

Showcasing local storage data in a textarea using React hooks

I am currently developing a note taking application using React. Successfully implemented state management with local storage. The objective is to display the 'notes' from local storage in the textarea upon rendering and refreshing. Currently, ...

Retrieving JSON data using JavaScript

'[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]' When attempting to retrieve the information above with the following code: for (var i = 0; i < data.length; i++) ...

What is the best way to find unique characters along with their frequency in JavaScript?

Can you help me adjust this code in order to receive the desired output: "T-1 r-1 a-1 e-1 " (other characters are repeating. So no need to print the others) function checkUniqueCharacters() { var uniqueChars = []; var count = 0; var full ...

Exploring navigation within a React application

After attempting to develop a react native application and finding it too difficult for my needs, I decided to switch to React. As a beginner in web programming, I recall learning about the concept of 'navigation' in react native, including vario ...

Tips for choosing a href link from a JSON data structure

I'm struggling with JSON. I have a JSON object that looks like this: {main: "<a href="www.google.com"><img src="google_logo.png"></a>"} This is just a small part of my code. For example, I access the "main" object with json.main an ...

Pile of memory depletion

Having some trouble with memory while trying to launch my react app using npm start. The error message reads: <--- Last few GCs ---> [12380:006AE720] 71751 ms: Mark-sweep (reduce) 1215.6 (1266.1) -> 683.3 (1175.2) MB, 195.0 / 0.1 ms (average mu ...

The submit button fails to produce any result

I have a submit button in a contact form that triggers PHP code to send an email. However, when I press the button nothing happens - not even the PHP code is displayed as it should be if PHP were not installed. Interestingly, I have tested other simple mai ...

Is there a way for me to move the dot icon along the dotline?

Here is the code snippet: jsFiddle I have successfully implemented a click event to change the style of selected dots in dotline. Now, my query is : How can I enable dragging functionality for the dot icon within dotline? Your assistance on this matte ...

Tips for Choosing an Option Using Selenium

Can someone please assist me? I am having trouble selecting an element because when I hover/click on the dropdown id='rfdSubMenu1396697749612', it becomes visible. If I move the cursor away, it becomes hidden. However, when I try to run the cod ...

The Bootstrap dropdown vanishes before I can even click on it

I recently encountered an issue with my Bootstrap dropdown menu on my website. After making some changes, the dropdown disappears after 1-2 seconds when viewed on a mobile phone. Interestingly, the original Bootstrap menu works fine, but not my customized ...

Tips on refreshing a div using jQuery while maintaining the functionality of addEventListener

Hi, I am facing an issue with updating the "div" element. The refresh works fine, but after refreshing when I try to click on the updated "div", the addEventListener in my JavaScript code does not seem to work anymore. Can someone please explain why this i ...

What is the process for accessing someone's birthday information using the Facebook API?

Working on integrating Facebook login and successfully retrieving user details such as first_name, email, etc. However, encountering an issue with fetching the birthday information. When attempting to call for birthday using the code snippet below, no data ...

Script in Javascript halting Internet Explorer's operation

I'm encountering a problem with Internet Explorer freezing due to the following code. This code is part of a project that focuses on handling student grades: var array1 = StudentGradeAreadHugeList(); var nextArrayItem = function() { var grade = ...

Loopback: Unable to access the 'find' property as it is undefined

I've come across a few similar questions, but none of the solutions seem to work for me. So, I decided to reach out for help. I'm facing an issue while trying to retrieve data from my database in order to select specific parts of it within my app ...

Textfield removal from the input range is requested

I recently encountered an issue with my input range HTML code. Here is the initial code snippet: <input class="sliderNoTextbox" id="ti_monatlich" type="range" name="ti_monatlich" data-theme="d"> After some adjustments based on this helpful answer, ...

Steps for replacing the firestore document ID with user UID in a document:

I've been attempting to retrieve the user UID instead of using the automatically generated document ID in Firebase/Firestore, but I'm encountering this error: TypeError: firebase.auth(...).currentUser is null This is the content of my index.js ...

Utilizing JavaScript for Interactive Check/Uncheck Feature in TreeView Nodes

I am currently utilizing the following JavaScript for implementing Check/Uncheck functionality for TreeView nodes checkboxes. The treeview contains three levels: parent, child, and siblings. Although the JavaScript code functions properly, I am in need ...

Rotating images on a canvas

We're currently implementing Ionic and Angular in our project. One issue we are facing is regarding image rotation on canvas. When we click on an image, the rotation works perfectly if it's a jpg file. However, when we pass a base64 image, the r ...