What is the best method for enabling CORS policy when making a fetch request from a Vue.js frontend to

I am currently facing an issue with my front-end code that is making a request to the back end

(frontend is running on localhost:8081 and sending a request to localhost:8080)

This is the front-end code snippet:

<script lang="ts">import 'vue-material/dist/vue-material.css'
export default {
  tasks: [],
  data () {
    return {
    }
  },
  methods: {
       BLABLA
  },
  created () {
    fetch('http://localhost:8080/getTasks')
      .then(response => {
        return response.json()
      })
      .then(tasks => {
        this.tasks = tasks
      })
  }
}
</script>

and this is the backend controller code:

import com.example.dto.TaskDto;
import com.example.model.Task;
import com.example.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
public class TodoListController {

    @Autowired
    TaskService taskService;

    @GetMapping(value = "/getTasks", headers = ("Access-Control-Allow-Origin: *"))
    public List<Task> getTasks() {
        return taskService.getAllTasks();
    }

    @GetMapping("/getTaskById")
    public TaskDto getTaskById(Long id) {
        return taskService.getTaskById(id);
    }

    @PostMapping("/updateTask")
    public TaskDto updateTask(TaskDto taskDto) {
        taskService.updateTask(taskDto);
        return taskDto;
    }
}

However, when I make the request, I receive the following error message:

Access to fetch at 'http://localhost:8080/getTasks' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Even after adding

@CrossOrigin(origins = "http://localhost:8081")

to the rest controller method in the backend, the same error persists. How can I go about resolving this issue?

Answer №1

Consider inserting @RequestMapping("/") between @RestController and @CrossOrigin while removing

headers = ("Access-Control-Allow-Origin: *")
. Spring may get confused if you fail to include RequestMapping at the class level or include additional headers at the method level.

@CrossOrigin(origins = "*", allowedHeaders = "*")
@RequestMapping("/")
@RestController
public class TodoListController {
    @Autowired
    TaskService taskService;

    @GetMapping(value = "/getTasks")
    public List<Task> getTasks() {
        return taskService.getAllTasks();
    }
    ...
}

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

`Cannot Get jQuery ScrollTop Function to Work for 2nd Element`

Having trouble with an issue. Let me explain. I implemented a scrollTop Jquery on page load that scrolls down after a delay to prompt user action. However, I'm facing a problem where another scrollTop doesn't work after clicking buttons "#b3,#b3 ...

LiveValidation plugin causing issue with removing dynamically inserted elements

My form validation is powered by the Live Validation plugin. After submission, the plugin automatically inserts a line of code like this one: <span class=" LV_validation_message LV_valid">Ok</span> However, I encountered an issue when trying ...

Determine whether a div contains any child elements

I am working on a piece of code that checks for the presence of the class "wrong" in any of my divs, and if found, displays a jQuery UI dialog box. My goal now is to enhance this code by adding a condition where it also checks for empty divs before showing ...

Exploring the process of generating, monitoring, and initiating personalized events in ReactJS

To establish a global custom event for listening and triggering purposes, here is how it can be achieved using jQuery: $(document).on('myCustomEvent', function(){ console.log("myCustomEvent triggered"); }) $(document).trigger('myCustom ...

NextJS application failing to display SVG icon in the absence of internet connection

https://i.stack.imgur.com/M9reE.jpg https://i.stack.imgur.com/Yyg4g.jpg Upon inspection of the provided images, it is evident that the src URL points to a location within the nextjs public folder. The issue arises when there is no internet connection - i ...

Adjust the width of the TinyMCE Editor to automatically resize based on the content being

Is it possible for TinyMCE to adjust the content within an absolutely positioned container and update the width while editing? <div class="container"> <textarea>This is my very long text that should not break. This is my very long text tha ...

Is there a way to retrieve cookie data from a component that has been rendered in _app.js using Next.js?

Within my next.js application, I have implemented a functionality where a hashed token from an OAuth2 provider is stored using cookies. Once the user completes the necessary steps, they are logged in and the cookie storing the token is set. The log in but ...

Ensure a button is automatically highlighted within an active class script

I have created a set of buttons that allow users to change the font family of the text. I would like the border and text color to update automatically when a specific option is selected. Currently, the JavaScript code works well, but when the page first l ...

Breaking down objects or arrays to extract specific values in React components

Some articles recommend using ES6 destructuring for React props & state as a best practice. For example: const { showModal, hideModal } = this.props; While I understand the benefits of cleaner code, I recently discussed with another developer who suggest ...

Updating state within a loop of properties in a React ComponentDidUpdate function

I have been working on a project where I needed to update the state after the componentDidMount lifecycle method. The props that I am expecting in the child component are only available at mount, so I can only update the state after that point. The only so ...

What is the best way to retrieve user data and format the output using JavaScript into a structured form?

I am trying to achieve the functionality shown in this image: https://i.sstatic.net/svzvc.png My goal is to extract user input from a form and display it on my webpage using JavaScript. Below is the code snippet that I have been working on. Code: f ...

Issues with $.ajaxSetup({async:false}) persisting in Internet Explorer

I have been trying to implement ajax file upload using the code below. It works perfectly in Firefox, but I encountered issues in IE. I specifically need a synchronous operation for which I set the async parameter to false: $.ajaxSetup({ async: false }); ...

Using the ES5 syntax with ag-Grid Vue

Can ag-grid-vue be used with ES5 without webpack or babel? I encountered the error below: Uncaught ReferenceError: exports is not defined at agGridVue.js:3 Is it possible to use ag-grid-vue with just pure javascript, or does it need a transpiler? ...

Retrieving the latest data iteration from the parent component

Is there a way to access the current data iteration from the template? I also need to obtain specific id's from the iterated elements. <template x-for="(datas, idx) in data"> <tr x-bind:class="idx % 2 == 0 ? &a ...

Doesn't the .stop(true) function completely clear the queue as it should?

My slideshow has a hover function to pause it using .stop(true). Upon mouse exit, it should resume playing from where it left off. However, currently, when I hover over it, the animation stops and then continues until it reaches its target, pausing there a ...

JavaScript: Retrieve the Number of Subscribers on the BroadcastChannel

Is there a way to check if a Broadcast channel exists and see how many subscribers it has? We have a product link, and some Chrome tabs are subscribed to a Broadcast channel. We want to determine the number of listeners. const bc = new window.BroadcastCha ...

A step-by-step guide on bringing in objects in JavaScript and Node.js

Let's say we have a file called main2.js exports.obj = { x: 10, setX: function(y) { this.x = y; }, getX: function() { return this.x; } }; Now, we also have two other files: abc.js const obj = require("./main2").o ...

The next.js application utilizing a custom server is experiencing rendering issues

Expanding my knowledge to next.js, I might be overlooking a simple aspect. My goal is to implement custom routes, so I crafted a server.js file and adjusted the command in my package.json to node server.js. Below is the entirety of the server.js file: con ...

I am having trouble accessing the child component $refs within the b-modal

When trying to access a child component's $refs within a b-modal, I encounter an issue. Upon page load, the vue dev tools reveal that "agent-edit" has not been created. If I move the component outside of the b-modal, it appears and is accessible -- b ...

Interacting with dynamically created input fields using Jquery from a JSON loop

I'm stuck trying to figure out why this code isn't working for me. I'm attempting to retrieve the value of a textfield that was generated via a loop from a JSON file. At the end of this code, I've added a simple click(function() {alert ...