【问题标题】:Sent Json to REST API - Access Control Allow Origin [ERROR]将 Json 发送到 REST API - 访问控制允许来源 [错误]
【发布时间】:2021-01-07 23:43:30
【问题描述】:

我想向我的 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)

【问题讨论】:

    标签: java ajax spring-boot vue.js xmlhttprequest


    【解决方案1】:

    您确定通过 xhr 发送是最佳解决方案吗?你为什么不使用获取? https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

    您的 vue 应用程序和 spring boot 应用程序在不同的端口上运行,并且浏览器将其视为不同的网站,这就是为什么它会因为 cors 而被阻止。其他添加cors头的解决方案,可以在js端代理。

    【讨论】:

    • 我还不确定。我不能在 IE 中使用 fetch。也许ajax是一回事
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-03-25
      • 2013-03-02
      • 1970-01-01
      • 2017-01-10
      • 2017-11-21
      相关资源
      最近更新 更多