如何解决将Json发送到REST API-访问控制允许源[ERROR]
我想将json发送到我的REST API。我尝试与邮递员,它工作正常。现在我想从前端发送数据。我不知道我需要在何处添加标题以及如何执行此操作。我在后端使用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/
,您确定通过xhr发送是最好的解决方案吗?为什么不使用提取? https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
您的vue应用程序和spring boot应用程序在不同的端口上运行,浏览器将其视为独立的网站,为什么会由于cors而被阻止。添加cors标头的其他解决方案可以是js端的代理。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。