JavaScript's POST method is failing to fetch data from the API, yet it is able to retrieve data successfully in

I am experiencing issues when trying to retrieve data from an API using JavaScript. The API works fine in Postman, but it is not functioning properly in JavaScript.

When I run the code, the console displays an error message stating "Failed to fetch response data" and shows 'undefined':

<!DOCTYPE html>
<html>
<head>
    <meta charset="ISO-8859-1">
    <title>Insert title here</title>
</head>
<body>
    <h2> Only Fetch API </h2>

    <script>
    fetch('https://smweb.in/hungaroo/app/api/plan_list', {
        method: 'POST',
        mode: 'no-cors',
        redirect: 'follow',
        headers: {
            "Accept": "application/json",
            "Access-Control-Allow-Origin": "*",
            "Content-Type": "application/json"
        }
    })
    .then(function (response) {
        return response.text();
    })
    .then(function(data) {
        console.log(data);
    })
    </script>
</body>
</html>

Answer №1

When utilizing the 'no-cors' request mode, it appears that the response generated is opaque in nature. Opaque responses lack a body, resulting in an empty response when attempting to log it. The Access-Control-Allow-Origin header should be set in the response object sent by the server, not in the request itself. Failing to include this header will lead to an uninformative response from the server. Adding 'no-cors' to the request is a workaround for obtaining an opaque response from an endpoint lacking the necessary Access-Control-Allow-Origin setting. For further clarification, refer to:

Attempting to utilize fetch with 'no-cors' mode

How to handle fetch response of 'opaque' type?

A question may arise regarding why Postman still functions in such scenarios. An informative read on this subject can be found at: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

It is worth noting that while the Fetch API adheres to same-origin policy restrictions, Postman does not.

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

Breaking the Boundaries of Fuzzy Search with JavaScript

I am currently utilizing ListJS's plugin for fuzzy search. It can be found at the following link: In an attempt to enhance the plugin, I implemented my own method to filter by the first letter of the items in the list. This involved selecting from an ...

What is the best way to name a force-directed Graph using d3?

I'm struggling to label the nodes in my force-directed graph created with d3.js. Despite trying various solutions from StackOverflow and online tutorials, I believe my issues stem from a lack of fundamental understanding of JavaScript. I've expe ...

Mapping a bar chart on a global scale

Are there any methods available to create bar charts on a world map? The world map could be depicted in a 3D view resembling a Globe or in a 2D format. It should also have the capability to zoom in at street level. Does anyone have suggestions or examples ...

JS: Issue with iterating over objects

Within my JavaScript code, there exists an object named box_object with the following structure: ({ id:"3", text:"this is a box object", connection_parent:["1", "2"], connection_child:["5", "6"], connectiondata_child:{ 0:{id:"5", ...

Solving Promises with Arrays in JavaScript

Currently, I am working on a project and facing an issue that I need help with. Let me give you some background on what I am trying to achieve. First, I am making concurrent API calls using Axios in the following manner: const [...result] = await Promise. ...

What causes variations in versions displayed by Node.js?

What causes this error to appear when using node version v16.17.1? https://i.sstatic.net/yJdEx.png ERROR: npm is known not to run on Node.js v10.19.0 UP--- I had multiple versions of node installed, with the default being an older version. I was able t ...

Generate menu options in real-time

I have developed a React single page application using the NASA Picture of the Day API. I am looking to incorporate a drawer feature that displays a history of previously shown images, but only showing their dates. However, I am unsure of how to dynamical ...

Tips on deactivating a button after it has been clicked once within a 24-hour period and reactivating it the following day with the use of JavaScript and Angular

Is it possible to disable my button after one click per day, and then automatically re-enable it the next day once a user has entered details using the submit button? I need assistance with JavaScript or AngularJS for this functionality. ...

Having trouble transferring file object from reactjs to nodejs

Hey there! I am relatively new to nodejs and React, and currently, I'm working on a project that involves sending a selected file from the front end (React) to the back end (Node). The goal is to upload the file and convert it into a JSON object. Howe ...

Tips on customizing the MSAL login commands for successful integration with numerous users

Successfully implemented the code to login using a username and password combination with Cypress for a webapp integrated with MSAL. In the end-to-end Testfile: describe('Login with MSAL as xxUsername', () => { beforeEach(() => { cy.Lo ...

Tips for restoring lost data from localStorage after leaving the browser where only one data remains

After deleting all bookmark data from localStorage and closing my website tab or Chrome, I am puzzled as to why there is still one remaining data entry when I revisit the site, which happens to be the most recently deleted data. This is the code snippet I ...

Can JavaScript be executed from the console while navigating between pages?

I am facing a challenge that I can't find any solutions for online or elsewhere. The task at hand seems straightforward. I am using the Chrome console and attempting to run Javascript code to navigate between pages with pauses in between. It feels lik ...

Automatic Clicks in the Chrome Console

I've come across a website that requires me to click on multiple elements scattered throughout the page Here is the code for one of the elements: <span class="icon icon-arrow-2"></span> Is there a way to provide me with the console comm ...

Ways to disperse items within another item

I have an inner object nested inside another object, and I am looking to extract the values from the inner object for easier access using its id. My Object Resolver [ { _id: { _id: '123456789', totaloutcome: 'DONE' }, count: 4 }, { ...

Implement a validation function in the "jQuery validation library."

Hello, I am currently using the jQuery validation plugin to validate my form. I am trying to add an additional rule to the validation, but I am struggling to get it to work. The input value should be less than or equal to the previous element's value. ...

Modify the `value` of the `<input type=color>` element

Hello there! I have been working on a feature where I need users to select a color and have that choice reflected in the value field. Initially, I assumed this could be achieved easily through Bootstrap's features since my project is based on Bootstr ...

Obtain the value of a URL parameter on a webpage without needing to refresh the

I have a list of records on a webpage, each with a unique URL pointing to another page with a parameter in the URL. When any of these records are clicked, I want to display the value of the URL parameter in an alert without reloading the page. <script& ...

Ways to receive attributes prior to the Render event

I am a beginner in React and encountering an issue with retrieving props from the parent before the child is rendered. https://i.sstatic.net/CLAdH.png My problem involves an Editor component that passes a string as props to a button. The string is collect ...

Enhancing TypeScript - Managing Variables within Namespace/Scope

Why is the console.log inside the function correctly logging the object, but after the function returns it logs undefined, failing to update the variable? In addition, when using this within testNameSpace, it returns window. Why is that? namespace testNa ...

The functions firebase.auth().currentUser and onAuthStateChanged consistently return null even when the user is logged in

Despite the fact that my front end Swift application indicates that the user is signed in, I am encountering an issue where firebase.auth().currentUser and the onAuthStateChanged listener in my node.js code return null. The backend service is called from t ...