Current CORS complications persisting with Vue 3, Axios, and ASP.NET Core Web API backend interaction

I am puzzled. While running my .net core server and loading the vue project in the same file, I encounter partial success. However, when I start testing the axios/fetch requests, the test project fails in other ways.

My CORS policy is set to be very lenient in .NET in Program.cs:

using Microsoft.EntityFrameworkCore;
using ToDoApp.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddCors(options => 
{
    options.AddPolicy("AllowOrigin", policy => 
       {
           policy.AllowAnyOrigin()
                 .AllowAnyMethod()
                 .AllowAnyHeader()
                 .WithOrigins("http://localhost:5173");
       });    
});

builder.Services.AddControllers().AddNewtonsoftJson();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<AppDbContext>(options =>
 options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"))
);

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors("AllowOrigin");

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

The relevant part of my controller for a basic GetAll request:

[Route("api/[controller]")]
[ApiController]
public class ToDoController : ControllerBase
{
    private readonly AppDbContext _context;

    public ToDoController(AppDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task<ActionResult<IEnumerable<ToDo>>> GetToDos()
    {
        return Ok(await _context.ToDos.ToListAsync());
    }
}

Details from my launchsettings.json:

{
 "$schema": "https://json.schemastore.org/launchsettings.json",
 "iisSettings": {
 "windowsAuthentication": false,
 "anonymousAuthentication": true,
 "iisExpress": {
 "applicationUrl": "http://localhost:40665",
 "sslPort": 44316
    }
  },
 "profiles": {
 "ToDoApp": {
 "commandName": "Project",
 "dotnetRunMessages": true,
 "launchBrowser": true,
 "launchUrl": "swagger",
 "applicationUrl": "https://localhost:7029;http://localhost:5096",
 "environmentVariables": {
 "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
 "IIS Express": {
 "commandName": "IISExpress",
 "launchBrowser": true,
 "launchUrl": "swagger",
 "environmentVariables": {
 "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}


Snippet from App.vue containing various attempts:

<script>
import axios from 'axios';
import {ref} from 'vue';

const API_URL = "http://localhost:5096/api/todo"

export default {
 setup () {
 const apiData = ref('');
 
 const loadApi = async () => {
 try {
 const response = await axios.get(API_URL);
 apiData.value = response.data.apiData;
      } catch (e) {
 console.error(e);
      }
    }
 loadApi();
 return apiData;
  }
}
</script>

<template>
 <header>
 </header>

 <main>
 <p class="p-quote">{{ apiData }}</p>
 </main>
</template>

<style scoped>
#app {
 font-family: Avenir, Helvetica, Arial, sans-serif;
}

.p-quote {
 color: white;
}
</style>

Despite multiple attempts and troubleshooting steps described above, I continue to face console errors similar to those shown in the images linked below. Help!

https://i.stack.imgur.com/RGMnH.png https://i.stack.imgur.com/3zgjM.png https://i.stack.imgur.com/jLhbL.png

Answer №1

When conducting local testing, it is important to enable access resources from any domain. To implement this functionality, replace the existing code with the following:

builder.Services.AddCors(options => 
{
    options.AddPolicy("AllowOrigin", policy => 
       {
           policy.AllowAnyOrigin()
                 .AllowAnyMethod()
                 .AllowAnyHeader()
                 .WithOrigins("http://localhost:5173");
       });    
});
builder.Services.AddCors(options => 
{
    options.AddPolicy("AllowOrigin", policy => 
       {
           policy.AllowAnyOrigin()
                 .AllowAnyMethod()
                 .AllowAnyHeader()
                 .WithOrigins("*");
       });    
});

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

Adding tags or slots to input fields in Vue

When working with Vue, I have implemented a basic input text field for user input. My goal is to generate removable slots based on the text entered by the user. There is a button labeled "add slot" which allows users to add their desired input. Please refe ...

Transfer the Vue query parameter from the current route to the router-link

Why is it so challenging to detect and pass query parameters in Vue components? I'm trying to access the router from my component, but nothing seems to be working. How can I achieve this? <router-link :to="{ path: '/', query: { myQue ...

A helpful guide on incorporating data from one component into another component in Vue.js

Recently, I started working with Vue and I am facing a challenge in transferring an array from one component to another. The first component contains the following data that I need to pass on to the second component: const myArray = []; Both components a ...

Transmitting data from express server to vue.js interface

Hey there, I am facing a bit of a complex situation and could really use some help. Here's what I've got: an application split into server-side using node/express and client-side with Vuejs. The issue arises when I try to create a user on the ba ...

Utilize data attributes in VueJS to dynamically style elements

Is there a way to utilize the data() values within the <style>..</style> section? I have experimented with different combinations (using/omitting this, with/without {{brackets}}, etc.) but haven't been successful. Interestingly, when I man ...

Using Vue.js to showcase real-time Pusher data in Laravel 5.4

I am currently working on developing a real-time chat application using vue.js, Pusher, and Laravel. I have successfully managed to receive information from Pusher, as I can view the JSON data in the console with the correct details. However, I am facing a ...

Postman successfully interacts with cookies, while VueJS encounters difficulties in doing so

Currently, I have a Flask server up and running on , along with a Vue.js frontend running on http://localhost:8080. The API has been set up and tested using Postman, with everything functioning seamlessly as expected. Upon sending a POST request to /log ...

Explore the integration of Vue.js and Laravel API for seamless and efficient web

I am struggling to implement a search function within a list of elements using Vue.js. Despite successfully displaying the list in a table, I encounter issues when attempting to filter the list based on a search term. Any assistance would be greatly appr ...

How can I verify a user's role in Vuex?

I'm currently working on verifying the user role during login in Vue.js. Utilizing Vuex for state management, my goal is to redirect users with role = 1 (admin) to the admin panel and those with role = 0 (user) to the user dashboard. However, I seem t ...

Inspecting the Nuxt.js application, retrieve the build version using console.log

Currently, my Nuxt site is being hosted on AWS S3 with Cloudfront. Whenever I deploy a new version, I have to invalidate the CloudFront CDN which causes a delay in the deployment process. I want to display the build hash by using console.log(buildHash) wh ...

What is the best way to show distinct items and their frequencies from an array of objects in Vue.js/JavaScript?

I have been developing an inventory management application using Vuejs, and I am facing a JavaScript-related challenge in my project. The issue revolves around handling data that includes user information retrieved from a form, as well as static categories ...

Implementing a Vue.js v-bind:style attribute onto a dynamically generated element post-page initialization

Let me start by explaining my current issue and dilemma: I have been tasked with converting an existing JS project into a Vue.js framework. While I could easily solve a particular problem using jQuery, it seems to be posing quite a challenge when it comes ...

Losing authentication token when refreshing with Nuxt asyncData and Axios

While testing a get API that retrieves an array of mail data through Postman, everything seems to be working smoothly. However, when I implement the asyncData method to fetch the array in my code, it only works once. Upon page refresh, I encounter a 401 er ...

Using v-model in Vue with jQuery integration

I wrote a jQuery code that is executed when the mounted hook runs mounted() { this.$progress.finish(); var geocoder = new google.maps.Geocoder(); var marker = null; var map = null; function initialize() { var $latitude = document.getEl ...

422 Unprocessable Entity Error: Rails API and VueJS Collaboration Issue

Currently, I am attempting to establish a new user using a vuejs form with a Rails API in the backend. For JWT authorization, I rely on the use of gem knock and gem bcrypt. Upon submitting the form, an error 422 is generated in the terminal. It seems tha ...

Having trouble with ASP.NET Core MVC Ajax call not sending parameters to the API controller method?

I'm having trouble calling an API controller method using ajax and passing parameters. The api method gets called, but the values come through as null in the controller method. Interestingly, using the same ajax call, another controller (not the api ...

Changing Vuex store state by using mapped actions within the render function of a Vue component

I have been working on a slider with a modal that should open when an image is clicked. The modal state is stored in my Vuex store, and I need to dispatch an action from the image tag within my render function. While following Vue documentation, I have at ...

Testing Vue's disabled input using Vuetify

Learning testing is a new challenge for me, and I'm navigating my way through the complexities of it. Today, I want to create a test for a Vuetify <v-text-field> component with the following structure: <v-text-field v-model="user.c ...

What are the steps to include a string into Vue and then assess its value?

Where should I define a function in a SPA using the options API that will be called from an HTML href? Check out this demo on Codepen where everything works fine: CODEPEN However, when I try to implement it in my single-page application: <templat ...

"Customize the number of items displayed per page with Bootstrap Vue's perPage

I am currently working on a Vue project which you can view on codesandbox and utilizing bootstrap-vue. Within the project, there are multiple columns containing cards along with pagination: <template> <b-container> <b-row :cu ...