首页 > 解决方案 > 将 Json 发送到 REST API - 访问控制允许来源 [错误]

问题描述

我想向我的 REST API 发送一个 json。我用 Postman 试了一下,效果很好。现在我想从我的前端发送数据。我不知道我需要在哪里添加标题以及我是如何做到的。我将 Springboot 用于我的后端,将 Vue 用于我的前端。我的控制器:

@RestController
@RequestMapping("/api/auth")
public class FileController {

FileService fileService;

public FileController(FileService fileService) {
    this.fileService = fileService;
}

@RequestMapping(
        value = "/data",
        method = RequestMethod.POST,
        consumes = "application/json")
public void process(@RequestBody String payload) throws Exception{
    System.out.println(payload);

    try {
        FileWriter writer = new FileWriter(...);
        writer.write(payload);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
   }
 }

我的 main.js,它将发送数据:

const toSend ={

"name": "test",
"test1":"test2"
 };

const jsonString = JSON.stringify(toSend);

const xhr = new XMLHttpRequest();

xhr.open("POST", "http://localhost:8090/api/auth/data");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(jsonString);
console.log(jsonString)

标签: javaajaxspring-bootvue.jsxmlhttprequest

解决方案


您需要为此控制器启用 cors。这件事有一个注释。查看本指南 https://spring.io/guides/gs/rest-service-cors/


推荐阅读