Axios - Dealing with CORS Policy

I am currently attempting to send a basic axios request in my Vue.js project:

axios
 .get(url),
 .then(({ data }) => {
    // ...
 })
 .catch(err => console.log(err))

However, I keep encountering the following error:

Access to XMLHttpRequest at 'url' from origin 'http://localhost:8080' 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.

Error: Network Error
    at createError (createError.js?2d83:16)
    at XMLHttpRequest.handleError (xhr.js?b50d:84)

I have already attempted adding the necessary headers without success:

headers: {
   "Access-Control-Allow-Origin": "*"
   "mode":"no-cors"
}

Interestingly, when I manually paste the URL into the browser's address bar, the request goes through successfully.

If anyone has suggestions or guidance on how to resolve this issue, I would greatly appreciate it. Thank you!

Answer №1

To summarize: If you don't have control over the API to enable CORS on the server side, but still want to use that API, then you'll need to create an API wrapper for your application.

This could be a node.js express API that simply takes your requests and forwards them (using axios) to the API. The advantage is that in a node.js environment, you're not restricted by the browser's CORS limitations.

You can find templates for this on platforms like Netlify, as well as numerous examples through Google searches.

Answer №2

Summarizing comments on the issue

CORS, or Cross-Origin Resource Sharing, is a security measure that ensures only authorized clients can access resources from different origins. It's like locking down your APIs so not just anyone can use them. To resolve CORS issues, the backend server needs to enable CORS either globally or for specific URLs. This requires tweaks in the backend code, but most programming languages have straightforward solutions for this.

If you're facing CORS errors when making Axios calls in Vue, it's likely because the server hosting the resource doesn't allow cross-origin requests. The browser can load the resource directly because it's from the same origin, but Axios requests trigger CORS checks. For more detailed information on solving CORS problems, check out this article:

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

Sharing information with views in node.js using express

I am working on my node app to retrieve data from an API and display it in a view while allowing users to make changes. The process involves calling the API, receiving a JSON response, and passing that data to the view. Here is the code snippet: var q ...

When using `Mongoose.find({})`, the result is an empty array

I'm having issues with my code where it's only returning an empty array when I try to fetch documents from the "Ingredients" collection. Here is a link to my "Ingredients" collection image: https://i.stack.imgur.com/Gpw8V.png Below is the ingre ...

Encountering numerous errors while attempting to upgrade from Angular 9 to Angular 11

On Thursday of last week, I initiated an Angular update and unfortunately, I have been encountering numerous errors ever since. The most recent error while running ng serve -o is: An unhandled exception occurred: ENOENT: no such file or directory, lstat &a ...

Dealing with parameters in nested routes within express.js: Best practices and tips

I've been exploring the possibilities of using nested routes for their easy way of passing variables. router.post('/postlinkone', function(req, res, next){ //define a few variables (x,y) //render or redirect to close this route router. ...

Running a Node.js child process upon clicking an HTML button

I need to create a basic webpage where clicking a button will open the command prompt. This is my goal. Below are the HTML and Node.js code snippets. test.html <html> <head> </head> <body> <p>guru</p> <form a ...

Struggling to get my package to install globally using npm install -g

I have been working on implementing CLI functionality into my npm package called intercept-proxy. Despite lacking clear documentation, I managed to piece together the necessary steps by referencing and modifying code from express.js. To enable CLI usage, ...

Confusion about the unwinding of the call stack in the Graph Depth-

Issue with function: hasPathDFSBroken Fix implemented in: hasPathDFS The updated version includes a forced parameter to address the issue, which I would prefer to avoid. I'm trying to comprehend why in the broken version, when the call stack unwinds ...

Change the headers of the request being proxied

Currently, I am working on IP restricting a pure client-side CORs demo application that connects with an authenticated third-party API. To facilitate this connection, I have set up a "middleware" server to act as a proxy for requests between the CORs app a ...

Creating a powerful combination: Building an Express backend integrated with a sleek React front-end

I am facing a bit of challenge in setting up the connection between my front-end and back-end logic. I'm simply trying to fetch data from Express to test if everything is working correctly, but it's proving to be quite difficult. Additionally, I ...

Encountering an error message of "[jwt is not defined]" when attempting to retrieve data from the MongoDB

Explaining the question - I am successfully registering users in a mongoDB database and generating an accessToken [jwt based]. However, when trying to query the database to fetch the list of users, I encounter the error: jwt is not defined. Also, mentioni ...

Exploring the power of Typescript functions within a traditional VueJS project

TL;DR: How can I import and use a typescript module into my plain js Vue-Components? I have a Vue 2 (not yet 3) project. In this specific project, I have made the decision to refactor some of the code logic into ES modules for improved testability and reu ...

Ways to address the CORS problem in an ajax function without relying on json

When I run my ajax function: function fn_nextitem(sliderNo){ $.get("/index.php?op=ajax", {slide_no:sliderNo},function(resp) { if (resp) { $('#Div').append(resp); } else { } } This is how my ph ...

Mongoose encountering an issue with undefined properties (specifically 'prototype') and cannot read them

I am currently using Mongoose 7.0.1 on Next JS 13.2.2 and React 18.2.0. After tirelessly searching for a solution to my problem, I am still struggling with connecting to a MongoDB. Every time I try to import mongoose into my project for the connection, an ...

Is it possible to include comments in mocha.opts?

Is there a way to include a comment in mocha.opts file? js test --recursive --reporter spec --require ./test/test.bootstrap --require ./test/server.bootstrap --slow 200 # --delay What is the best way to disable or comment out the last line? ...

Best practices for passing multiple values with keys in vue.js when constructing URLs

I am working with this data containing various attributes: for(var k = 0;k<this.form.fields.length;k++) { this.dynamic_fields.push({attribute_id:attributes[k].id,value: attributes[k].value}) ...

Mastering the art of binding values within nested JSON structures

I am looking to establish two-way binding with my JSON data, so that when a value changes in an input field, it will also update the corresponding value in the 'data' section. I believe using the 'bind' directive is the best way to achi ...

Throw an error message: `@grpc/grpc-js is only compatible with Node ${supportedNodeVersions}` in Dialogflow

I am attempting to recreate the example from the Dialogflow Blog: The code snippet is as follows: 'use strict'; const admin = require('firebase-admin'); const dialogflow = require('dialogflow'); // Fetching credentials ...

Why won't my Node.js server register a connection from a Swift client using Socket.IO?

I'm facing an issue with my Swift and Xcode setup. It seems like the server connection is established in Swift/Xcode, but my Node.js file doesn't log 'a user has connected' in the terminal. This is a repost of my original question, as I ...

Ways to identify when a user presses the back or forward arrow on a browser using JavaScript or jQuery for a non-single page application (

There are only 2 routes available: / and /about When on the following URLs: localhost:8080 -> it displays the home page localhost:8080/about -> it shows the about page If a user opens the home page, clicks on the about button, and goes to the abou ...

Encountering an issue stating: "[Vuetify] v-ripple can only be applied to block-level elements" while attempting to deploy on Heroku platform

Lately, I've been working on developing an app using Rails 6 with a mix of Vue and Vuetify for the front end. Everything runs smoothly on my local machine. However, as soon as I attempt to deploy it on Heroku, I encounter this error in the debug conso ...