java - 将 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)
解决方案
您需要为此控制器启用 cors。这件事有一个注释。查看本指南 https://spring.io/guides/gs/rest-service-cors/
推荐阅读
- python - 使用 softmax 激活的二元分类总是输出 1
- postgresql - pgo:计划备份的计划保存在哪里
- firebase - Flutter Stean builder运行initialay并显示错误在null上调用了getter'length'。但是在手势检测器单击后它运行正确
- typescript - 使用附加数据扩展 Typescript 泛型
- angular - 为什么 ngOnInit() 会为 setInterval() 执行多次?
- mysql - 带有正则表达式的 SQL 过程中的两个反斜杠
- azure-active-directory - AADSTS5002710:无效的 JWT 令牌:标头格式错误
- python - 使用 pandas apply 来传递一行和整个数据框
- r - 宽到长,有许多不同的列
- java - 从 java poi 4.1.2 中的 excel 表中读取国际货币符号