Axios encounters CORS issues, while fetch operates smoothly

After going through various questions on CORS errors to no avail, I am facing a dilemma in my NuxtJS client application. Whenever I try to make a simple POST request using axios, I encounter CORS issues. However, when I switch to using the fetch API, everything works smoothly. Although the server has the correct "Access-Control-Allow-Origin" headers set, neither option below functions when that header is removed. Can anyone shed light on why fetch works fine but axios doesn't?

FAILS

await this.$axios({
      url,
      method: 'POST',
      data
    })

WORKS

await fetch(url, {
      method: 'POST',
      body: JSON.stringify(data)
    })

Error message: Access to XMLHttpRequest at {URL} from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

In the network tab of Chrome, the request headers show as follows:

Axios request headers

fetch request headers

Answer №1

When sending data in the body of an HTTP request, the Content-Type header specifies the type of data being sent.

If you are sending JSON, the header should be Content-Type: application/json.

With axios, when passing an object, it automatically encodes it as JSON and sets the appropriate Content-Type header.

However, with fetch, encoding the data and setting the Content-Type must be done manually. If not set properly, fetch assumes plain text instead of JSON.

The fetch code contains errors.


When POSTing data using a format that can be sent via a regular HTML form, there are no special CORS requirements due to historical reasons. text/plain is an example of such a format.

Unlike application/json, which requires a CORS preflight request for permission, leading to restrictions between browsers and servers.

If the server does not grant permission, it should respond with something similar to:

HTTP/1.1 204 No Content
Connection: keep-alive
Access-Control-Allow-Origin: https://foo.bar.org
Access-Control-Allow-Methods: POST, OPTIONS
Access-Control-Allow-Headers: Content-Type
Access-Control-Max-Age: 86400

Answer №2

Consider including the withCredentials option:

axios({
    method: "POST",
    url: "https://....",
    data: {},
    withCredentials: true
})

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

The function req.isAuthenticated() always returns false and never evaluates to true

My goal is to create user authentication using the following code: userRouter.post("/login", passport.authenticate("local", { session: false }), (req, res) => { if (req.isAuthenticated()) { const { _id, username } = req.user; const t ...

I am having trouble printing because of document.write

Whenever I use javascript to create a document with document.write I include an iframe element then I try to print the contents using iframe.print() but nothing happens - no error message and no print dialog box. How can I successfully initiate a print ...

Tips for incorporating a Python script into a online project

I've been working on a Python code that detects faces and eyes using face recognition. When the code runs in PyCharm, it displays a camera window. Now I'm trying to figure out how to integrate this window into a webpage project written in HTML, C ...

What is the reason for the find() method not displaying the most recent data from a MongoDB database in an Express.js application?

Upon calling the app.post('/form-submit', funtion(req, res)) method, my expectation is for it to first save the data using save(). This works fine, but then when I call the find() method, it shows all the data from the mongoDB database except for ...

Issues with user-generated input not properly functioning within a react form hook

After following the example provided here, I created a custom input component: Input.tsx import React from "react"; export default function Input({label, name, onChange, onBlur, ref}:any) { return ( <> <label htmlF ...

Exploring the power of V-for with checkboxes in VueJS

One issue I am facing is related to triggering my save method only when a checkbox is selected or true in Vue JS. I have no problem listing values and saving them to the database using axios, Vue JS, and Spring Boot. However, every time I click the checkbo ...

Analyzing past UTC date times results in a peculiar shift in time zones

When I receive various times in UTC from a REST application, I encounter different results. Examples include 2999-01-30T23:00:00.000Z and 1699-12-30T23:00:00.000Z. To display these times on the front end, I use new Date(date) in JavaScript to convert the ...

How can I obtain the true client IP address using Nginx?

I have a straightforward express app that has been containerized using Docker. You can find the repository here. In this setup, I utilized nginx as a reverse proxy. When accessing http://45.33.97.232:3000, it displays the actual server IP. However, if I v ...

What is the process for obtaining intersection set data from an array?

I'm trying to find the intersection set within an array only containing type 1 and 2. Can you help me with that? var arr = [ { id: 1, auths: [ { authId: 1, type: 1, value: 'Test1' }, { authId: 2, type: 1, ...

I am looking to have the first option in the dropdown menu appear as a placeholder text

In my form, I have two phone number fields - one for mobile phone and the other for home phone. I need to make only one of them mandatory. Can someone please advise me on how to accomplish this? ...

Having trouble setting the backgroundImage in React?

Hi there! I'm in the process of crafting my portfolio website. My goal is to have a captivating background image on the main page, and once users navigate to other sections of the portfolio, I'd like the background to switch to a solid color. Alt ...

Using jQuery's .live('click') method will only bind to the initial element found on the webpage

I developed a custom jQuery plugin that attaches to 8 different elements on a webpage. Within each element, I intended to utilize the .live() method to bind a click event to a link, triggering a form submission via ajax. However, I encountered an issue whe ...

What is the most effective method for incorporating access token authentication in a React application?

As a newcomer to React, I am working on implementing authentication using Express.js in my react web application. I have successfully set the token in response cookies on the backend with the HttpOnly flag, but unfortunately, I am unable to read it on the ...

The use of `await` within a loop may not function as anticipated when the code is being run through Puppeteer, yet it functions flawlessly when executed in the browser's console

Currently, I am assessing the functionality of the codeToBeEvaluated function within a browser environment using puppeteer. Within codeToBeEvaluated, there is a while loop designed to trigger an alert (referenced as LINE B) every 10 seconds. The issue ari ...

What is the best way to prevent useEffect from triggering when a modal is being rendered?

I'm currently developing a react movie application. I am facing an issue with the hero picture feature that displays a random popular movie or show. Whenever I click the button to open a modal, the useEffect function is triggered and changes the movie ...

Is there a way to dynamically include a peer dependency in a file that is bundled using webpack?

I am currently developing a plugin that relies on jQuery as a peer dependency. However, when I attempt to import this plugin into my primary project (which already has jQuery installed), I encounter the following error: Module not found: Error: Can't ...

Approach to retrieving data with Nodejs API

Currently, I am working on a project with Node.js and using Express.js. My goal is to retrieve data from a MySQL database, but I encountered the following error: "await is only valid for async function" How can I resolve this issue? Below is the ...

A guide on extracting a JSON data with a BigInt type using TypeScript

I am facing an issue with parsing a bigint from a JSON stream. The value I need to parse is 990000000069396215. In my TypeScript code, I have declared this value as id_address: bigint. However, the value gets truncated and returns something like 9900000000 ...

Utilize the Bootstrap responsive grid system to ensure that every row is filled with content, creating

I am working with a list of 8 results that I display in a responsive bootstrap grid. However, I want to only show the results that fill up entire rows. For instance, on a medium-sized screen, it appears as 2 rows with 4 results each. On a smaller screen, ...

Vue search button not returning results

Hello, this is my HTML file. <div id="app1" v-cloak> <input v-model="term" type="search"> <button @click="search">Search</button> <p/> <div v-for="post in posts" class="post"> ...