[英]Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Java Backend with CrossOrigin("*") annotation
I know that there are a lot of questions regarding this topic, but after a few hours of trying multiple fixes I haven't been able to make it work.我知道有很多关于这个主题的问题,但在尝试了多个修复几个小时后,我还是没能解决这个问题。
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequestMapping("/api/bag")
public class RestBagController {
My controller currently accepts any cross origin requests.我的 controller 目前接受任何跨源请求。
The issue seems to be with this particular method that consumes multipart/form-data问题似乎出在这种使用 multipart/form-data 的特定方法上
@PostMapping(consumes = "multipart/form-data", path = {"/image"})
public ResponseEntity<?> saveImages(@RequestParam("file") MultipartFile[] files) {
Finally, my ajax request最后,我的ajax请求
var blobFile = $("#serialcodefile").prop('files')[0];
var formData = new FormData();
formData.append("serialcodefile", blobFile, "serialCode");
$.ajax({
url: "http://localhost:8080/api/bag/image",
type: "POST",
data: formData,
headers: {
'Content-Type': 'multipart/form-data'
},
processData: false,
async: true,
success: onSuccess,
});
My backend is hosted in localhost:8080 and the frontend on localhost:5501.我的后端托管在 localhost:8080 中,前端托管在 localhost:5501 中。
Also I'm not sure if relevant, but once I press the submit button on the form, I make 2 POST requests.我也不确定是否相关,但是一旦我按下表单上的提交按钮,我就会发出 2 个 POST 请求。
From jquery docs - contentType
(default: 'application/x-www-form-urlencoded; charset=UTF-8')来自 jquery 文档 - contentType
(默认值:'application/x-www-form-urlencoded; charset=UTF-8')
Here is the link to docs - https://api.jquery.com/jquery.ajax/ Search for ContentType here.这是文档的链接 - https://api.jquery.com/jquery.ajax/在此处搜索 ContentType。
Can you try by removing headers
and instead add ContentType:false
.您可以尝试删除headers
并添加ContentType:false
吗? Hope this works!!希望这有效!
$.ajax({
url: "http://localhost:8080/api/bag/image",
type: "POST",
data: formData,
ContentType: false,
processData: false,
async: true,
success: onSuccess,
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.