fetch() operates successfully in Extension but encounters difficulties in Chrome Console/Snippet

I am currently facing an issue with my Chrome Extension. The extension performs a successful GET request, but when I try to replicate the same action in the Chrome Console or Snippets, I encounter errors. Here is a minimal example of the code I am using:

fetch(url, {
    method: "GET"
}).then(response => response.text())
  .then(html => console.log(html))
  .catch(error => console.log(error))

However, when running this code outside of the extension environment, I receive the following errors:

TypeError: Failed to fetch for the error and

Failed to load resource: net::ERR_FAILED
in Chrome's inline error marker

Although I have tried adjusting headers in my AWS Lambda function to potentially resolve any CORS issues, the problem persists. This leads me to believe that CORS might not be the root cause of the issue.

My requests do not seem to leave my machine as they are not visible in AWS CloudWatch. Even testing on a clean Chrome User profile yields the same results. To rule out any server-related problems, I have also tested examples from this source.

async function testGet() {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts')
    console.log(await response.json())
}

async function testPost() {
    let r = await fetch('https://jsonplaceholder.typicode.com/posts', {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            lockevn: 1
        }),
    })
    console.log(await r.json())
}


testGet()

testPost()

When monitoring the network activity in Chrome's Network tab, the request appears to be stalled.

The explanation provided about the queueing and stalled states does not seem to offer a clear solution to my current predicament. Despite restarting my browser and ensuring no disk cache allocation problems, the issue persists. Any insight into resolving this matter would be greatly appreciated.

Answer №1

After some investigation, I was able to identify the issue. To ensure that my requests were not being given special treatment by accessing the Chrome Developer Console in my AWS dashboard tab, I decided to conduct my testing on a new tab (chrome://new-tab-page/). This approach led me to encounter the errors that I described.

Before sharing my code with others for validation, I wanted to confirm that it was running correctly. To quickly check this, I used the Console on the Stackoverflow tab and it worked as expected. My intention was simply to verify if the code was interpretable, but to my surprise, it returned a result. The same behavior was observed when running it on an HTTPS website on my AWS instance. Although undocumented, it seems that the presence of "disk cache" could be a contributing factor to such errors.

In short, avoid opening Chrome Console in a new tab for making requests in the console; use any website instead.
It is possible that CORS headers may only function properly if the request does not contain empty headers initially, perhaps?

I opted against using a website's console for testing purposes to prevent any potential interference from cookies on the AWS page, which could differ from what someone else experiences on their machine. It seemed like a good precaution at the time, but turned out differently!

Thank you for your valuable suggestions and assistance. Your input has been greatly appreciated.

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

When installed globally, Yeoman generator is unable to locate the .yo-rc.json file

My yeoman generator is almost ready to go, but it heavily relies on the .yo-rc.json file for important configurations. While it works fine when run from the project's directory, I encounter issues when trying to run it from another project, even after ...

The cancel button is experiencing unexpected behavior when used in conjunction with the jQuery load event

I'm experiencing an issue with a cancel button on my website. After clicking the cancel button, it cancels the action but then proceeds to reload the page. I attempted to fix this by adding the "preventDefault" method, but it did not resolve the iss ...

Exploring the Dynamic Connection: AngularJS and MongoDB

As someone who is new to MEAN stack, I am currently working on creating a simple one-page application. My goal is to connect to MongoDB and retrieve values from a specific collection using a controller. During my search for an answer, I stumbled upon this ...

Creating unique IDs for movie pages with NUXT using data retrieved from the movie DB API

Here is the breakdown of my folder structure: https://i.sstatic.net/X2CHX.png This showcases how the page appears: https://i.sstatic.net/Zul87.jpg I have successfully retrieved all the necessary data from props. However, I am struggling to comprehend h ...

How can I prevent div duplication when working with ui-router?

I created a basic demonstration to get familiar with ui router. Unfortunately, I encountered an issue of duplicated views when utilizing ui router. Below is the snippet of the stateProvider section: app.config(function($stateProvider,$urlRouterProvider) ...

How does the Angular2-all.umd.js compare to the angular2.js file?

Currently, Angular 2 is in its 13th beta phase. I came across https://code.angularjs.org/2.0.0-beta.13/ and noticed that there are two different versions of Angular2 available: angular2-all.umd.js angular2.js What distinguishes these two versions from ...

How can one create parameter information in JavaScript?

Is it possible to automatically generate parameter information in JSDoc style based on function implementation? /**  * Assigns the project to a list of employees.  * @param {Object[]} employees - The employees responsible for the project.  * @param {st ...

The error message "Cannot read property 'option0' of undefined" occurs when using Node.js with Express and EJS

script.js var choices = { choice0: 11, choice1: 'choice1', choice2: 'choice2', choice3: 'choice3', choice4: 'choice4', choice5: 'choice5', choice6: 'choice6', choice7: 'choice7', choice ...

AngularJS Router and .NET backend - troubleshooting templateUrl redirections

I am currently working on developing an Angular application that utilizes $routeProvider. The backend of the application is built using .NET, which serves HTML files tailored with specific permissions and roles for my app. Occasionally, when a certain acti ...

What steps are involved in creating a circular shape on canvas?

I am trying to create a circular shape in the canvas using the code below. The code involves moving an object with keyboard keys, and I need help making the canvas shape into a circle without affecting the functionality of the code. I attempted to modify t ...

Stylelint causing issues when running as an npm script

I have configured stylelint for my project and it is running smoothly from the command line. Here is an example of the output when I run the following command: $ stylelint 'css/**/*.css' --fix css/style.css 20:18 × Expected newline after ": ...

How can I use Chart.js to assign a unique color to each x-axis label?

I'm currently using Chart Js to create a chart and I want each label to have a different color instead of all labels having the same color. Is there a way to achieve this using the ticks callback function? scales: { xAxes: [{ ...

Canvas Frustratingly Covers Headline

Several months ago, I successfully created my portfolio. However, upon revisiting the code after six months, I encountered issues with its functionality. Previously, text would display above a canvas using scrollmagic.js, and while the inspector shows that ...

The onclick function fails to function properly following an Ajax reload of the <div> element

I have an issue with my onclick function that only works the first time. Every time the onclick function triggers an ajax request, it successfully reloads a div which contains code to retrieve values from SQL and build an HTML table using a for loop. Alth ...

Send the useState function as a prop

I've encountered a challenge while attempting to pass a useState function named setState to a custom component. Despite several attempts, I have been unsuccessful in achieving the desired outcome. This is how I am invoking my custom component: const ...

Angular: The function t(...) does not support success - TypeError

My code is generating the error TypeError: t(...).success is not a function. I have tried searching for a solution but haven't been able to figure out why this error is happening in my specific case. Here is a snippet of my JS code. Can anyone point ...

Is there a way to make my DIVS update their content dynamically like buttons do, without manually adding an onclick function in the HTML code?

I am currently customizing a WordPress theme that lacks the option for onclick events on div elements. However, I can assign classes and IDs to them. In my design, I have four spans in a row, and when each span is clicked, I intend for the corresponding p ...

Tips on extracting a value from a subscription

I am trying to figure out how to pass a value from a subscribe function to a variable so that I can manipulate it later on. For example: getNumber: number; I need to be able to access and use the variable getNumber in the same .ts file. someMethodT ...

How can I refresh a window in Internet Explorer without it taking focus away?

Occasionally, I have a page where I need to update the URL with certain GET parameters in the background using JavaScript. This allows the page to refresh with the new parameters. For instance, I might use: window.location.href = window.location.host + & ...

Is it possible for web browsers to set a timeout on an XmlHttpRequest while it is still active?

When dealing with asynchronous XMLHttpRequests that take a long time to retrieve data from the server, I am searching for a way to abort them. Setting a timeout before sending the XHR is not feasible due to the length of these requests. Although calling X ...