我已经使用API
实现了Spring Boot
,并允许CrossOrigin
在我的域中。
看起来像这样
// Endpoints start here ... ironic right?
@RestController
@CrossOrigin(origins = {"http://localhost:8080", "http://a.example.com"})
public class FileController {
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
@Autowired
private FileStorageService fileStorageService;
// Upload file endpoint
// POST
@PostMapping("/uploadfile")
.
.
.
}
我在SO
上关注了许多类似问题的答案,但似乎没有用。 API
适用于Postman
,但是当使用front-end
和jQuery
实现Ajax
时,我在firefox
上收到以下错误。
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://a.example.com/fileupload/uploadfile. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).[Learn More]
我应该在哪里允许CORS
?我应该怎么做?
我的代码如下。
var max_fields = 10;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 0;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append(`
<span>
<br>
<div class="row" id="field[${x}]">
<div class="col">
<input type="text" name="fileName" id="field[${x}]-fileName" class="form-control" placeholder="File name">
</div>
<div class="col">
<div class="custom-file">
<input type="file" class="custom-file-input" name="fileUpload" id="field[${x}]-fileUpload" aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="fileUpload">Choose file</label>
</div>
</div>
<div class="col">
<input type="text" id="field[${x}]-fileUploadURL" name="fileUploadURL" class="form-control" placeholder="File URL" readonly>
</div>
<div class="col">
<button class="remove_field btn"> Remove Field </button>
</div>
</div>
</span>
<script>
document.getElementById("field[${x}]-fileUpload").onchange = function(e) {
e.preventDefault();
console.log("FILE UPLOAD OF field[${x}]");
var filePath = $(this).val();
var form = new FormData();
form.append("file", filePath);
var settings = {
"async": true,
"crossDomain": true,
"url": "http://b.example.com/fileupload/uploadfile",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-cache",
"Postman-Token": "f404898e-4229-4a14-933f-51e9b05c6628"
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
}
$.ajax(settings).done(function (response) {
console.log(response);
});
};
</script>
`);
}
});
答案 0 :(得分:0)
尝试将allowCredentials = "true"
和origins = "*"
添加到@CrossOrigin
中,
@CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*")
您可以根据需要更改origins
和allowedHeaders
的值。