Chris Garsonn
Chris Garsonn

Reputation: 777

How to allow cors policy on fetch of vue.js to backend?

I have a front-end code which is making a request to back end

(frontend is working on localhost:8081 and request is going to localhost:8080)

Front end code is:

<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 backend controller is:

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;
    }
}

whenever request is done, I got

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.

error. I added

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

to rest controller method on backend but still i got same error. How can I solve this problem ?

Upvotes: 0

Views: 535

Answers (1)

onuriltan
onuriltan

Reputation: 3898

Try adding @RequestMapping("/") between @RestController and @CrossOrigin and delete headers = ("Access-Control-Allow-Origin: *"). It is confusing Spring if you don't add RequestMapping in class level or adding extra headers in method level I believe.

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

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

Upvotes: 5

Related Questions