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?