如何允许将 vue.js 获取到后端的 cors 策略?

Chr*_*onn 0 javascript spring http-headers cors vue.js

我有一个前端代码,它正在向后端发出请求

(前端在 localhost:8081 上工作,请求将转到 localhost:8080)

前端代码为:

<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>
Run Code Online (Sandbox Code Playgroud)

和后端控制器是:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

每当请求完成时,我得到

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.
Run Code Online (Sandbox Code Playgroud)

错误。我加了

@CrossOrigin(origins = "http://localhost:8081")
Run Code Online (Sandbox Code Playgroud)

在后端休息控制器方法,但我仍然遇到同样的错误。我怎么解决这个问题 ?

onu*_*tan 5

尝试@RequestMapping("/")@RestControllerand@CrossOrigin和 delete之间添加headers = ("Access-Control-Allow-Origin: *")。如果您不在类级别添加 RequestMapping 或在我相信的方法级别添加额外的标头,这会使 Spring 感到困惑。

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

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