axios GET and POST requests are not functioning properly, while fetch requests are successful

I recently set up a REST API on Heroku using Express, NodeJS, and MongoDB (mogoose as orm and MongoDB Atlas as well). I am diving into the world of MERN stack development as a beginner 😅

If you want to check out the API, here's the link:

<a href="https://mern-deploy-test-adib.herokuapp.com/api/todos">/api/todos</a>

Everything seemed to be working smoothly with Postman and VS code's API plugin, as well as when accessing the API from localhost.

However, I encountered an issue when trying to GET/POST using axios, which resulted in the following error:

Error: "Network Error"

It's interesting to note that fetch() works without any problems, just like Postman.

Additionally, I noticed a CORS warning in the console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at . (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://localhost:3000/’)

Even though I set the CORS like this:

app.use(cors({ origin: 'http://localhost:3000/', credentials: true }))

Strangely enough, the API worked perfectly on localhost but started facing issues with axios after deployment.

I made sure to set

cors origin: 'http://localhost:3000/'
And I compared the headers of both the fetch and axios GET requests. Surprisingly, they are identical.

The request header includes

Access-Control-Allow-Origin http://localhost:3000/

By the way, my frontend is hosted on localhost:3000

So, why is axios failing while fetch is successful?

Edit: Here is the code for both the axios and fetch request.

//fetch
fetch(`https://heroku-api-link/api/todos`)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err))

//axios
axios.get(`https://heroku-api-link/api/todos`)
.then(data => console.log(data))
.catch(err => console.log(err))

EDIT #2: I tried sending an axios request using an editor on my phone (SPCK editor), and the request was successful. I can't figure out why it's not working when I try from my PC.

Answer â„–1

After some investigation, I finally cracked the code! It turns out that the culprit was the origin link I had set in the cors. Initially, I had set the origin to http://localhost:3000/. Strangely, despite the client origin also being http://localhost:3000/, it didn't match the server's origin. However, when I tweaked the server cors origin to http://localhost:3000, removing the trailing '/', the issue miraculously resolved itself. While I am grateful it worked, I am left pondering the reason behind its success. Could it be related to a specific route? Perhaps adding the '/' restricts access only to the 'Home' route?

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

Is it possible to trigger an ajax function within the success section of another ajax function?

How can I use ajax to refresh specific sections of my HTML code once one ajax function is successful? My issue arises after the first ajax function saves data to the database, and I need to update the data on the page. ...

iPython does not show Folium map due to an error message stating: 'Uncaught ReferenceError: L is not defined'

Attempting to showcase a basic map in iPython using the Folium leaflet library. Recently installed iPython via Anaconda with Folium added through Pip. Verified that everything is fully updated Ran this code in iPython import folium map = folium.Map(locat ...

What is the best way to retrieve the value of the first name using Protractor?

Is there a way to store the value of the first name using a protractor script? The first name is set when the user logs in and corresponds to the name of the logged-in user. I am wondering if this can be done utilizing by.addLocator(). Here is the tag tha ...

Creating a js.erb file that functions independently of ajax in Ruby on Rails 4

I am currently working on a project with the following setup: index.html.erb -> link_to "click me " , 'customers/index' , :remote => true . controller -> customers def index end index.js.erb alert('in my js file'); The ...

An error has occurred in nodejs: headers cannot be set after they have already been sent

I'm a newcomer to Node.js and encountering some challenges. Whenever I attempt to open 127.0.0.1:3000/bejelentkezes, I encounter the following error: POST /bejelentkezes 500 550.784 ms - 2259 GET /css/404.css 304 2.751 ms - - 1 Successful login Erro ...

Registration process in Node Express application encounters persistent loading when accessed through Postman

I've been working on a signup model for user accounts in Node.js, but when testing it in Postman, I encountered an issue where there was no response or failure. This left me stuck and I received the following error message in my terminal: Unhandled ...

transform the stationary drawing to the top and left position at coordinate (0,0)

Exploring canvas has led me to encounter a puzzling issue with the translate method. While working on this fiddle http://jsfiddle.net/claireC/ZJdus/4/, my goal was to have the drawing move and bounce off all four walls. However, I noticed that it would no ...

Angular fails to function properly post rendering the body using ajax

I recently created a HTML page using AJAX, and here is the code snippet: <div class="contents" id="subContents" ng-app=""> @RenderBody() @RenderSection("scripts", required: false) </div> <script src="http://ajax.googleapis.com/ajax/ ...

What are the best techniques for effectively employing jQuery Deferred/promise in automatically invoked functions like .ajax()'s beforeSend()?

In my project, I am customizing jQuery's ajaxPrefilter to enhance the functionality of AJAX requests. Specifically, I am adding header data to the XHR request using setRequestHeader() within the beforeSend() method. The challenge I am facing is that b ...

How to retrieve all the text inside an element using Protractor and Selenium

<div class="test"> <span> <div>CONTENT </div> </span> <div> <ul> <li> <span>More text</span> EXAMPLE1</li> <li>EXAMPLE2</li> ...

Encountering error message "Module not found '@angular/compiler-cli/ngcc'" while attempting to run "ng serve" for my application

Encountering an error while trying to run my app, I have attempted various solutions available online. These include uninstalling and reinstalling angular/cli, verifying the correct version in package.json (ensuring it is "@angular/cli" and not "@angular-c ...

Tips for checking form input validity prior to opening a modelDialog

After successfully validating all required form fields, I am trying to open a modal dialog. Although I have managed to validate the form, I am struggling to write the code that will trigger the opening of the modal dialog upon successful validation. Do y ...

Is it possible to alter objects through the use of jQuery.map?

I'm working with a key-value pair that looks like this: var classes = { red: 'Red', green: 'Green' }; Is there a way to add a specific value before each key in the pair? Can jQuery.map help with this task? The desired end result ...

Dealing with recursion issues. What are effective solutions?

Having a small issue with my recursion. I've created a function that checks for matching directions of clicked boxes. const checkMatchingDirections = (board, r, c) => { const top = board[r - 1] !== undefined && { row: r - 1, column: c }; ...

Unable to concatenate values from Object in JavaScript

Although it may seem trivial, the following code is giving me trouble: window.temp1.targetInterests It gives me back: Object {Famosos: "Famosos", Musica: "Música", Humor: "Humor"} I attempted to join it: window.temp1.targetInterests.join('/&apos ...

What could be the reason for the lack of functionality in this jQuery code when combining a for loop with the $

<!DOCTYPE html> <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ for(let i = 0 ...

Guide to filling a dropdown menu by aligning with the text it contains?

I've set up two dropdown select boxes below that are exactly the same: HTML <select id="ddl1" name="ddl1"> <option value="1">TEXT 1</option> <option value="2">TEXT 2</option> <option value="3">TEXT 3&l ...

Designing Interactive Circular Dates on Website

Currently, I am working on a webpage using HTML, CSS, JavaScript, and PHP. The goal is to design a page that features 7 circles representing the current date and the next 6 days. Users should be able to click an arrow to navigate to the following 7 days. ...

Having issues with v-for in Vuejs? It seems to be looping multiple times

<div v-for="item in items" :key="item.id"> <div v-for="accordion in accordions" :key="accordion.title" class="line" :class="{ green: accordion.text === 'AllaboutVue', red: accordi ...

Adding a fresh element to an object array in TypeScript

How can we add a specific value to an array of objects using TypeScript? I am looking to insert the value 1993 into each "annualRentCurrent" property in the sample object. Any suggestions on how to achieve this in TypeScript or Angular? Thank you! #Data ...