简体   繁体   中英

Ajax - Cross-Origin Request Blocked - ‘Access-Control-Allow-Origin’ missing - Spring Boot

I have implemented an API using Spring Boot and allowed CrossOrigin on my domains.

It looks something like this

// 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")
    .
    .
    .


}

I've followed the answers of many similar questions on SO , yet it doesn't seem to work. The API works on Postman but when implementingthe front-end using jQuery and Ajax I get the following error on 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]

Where else should i allow CORS and what should i do?

My code looks like this.

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>
        `);
    }
});

Try adding, allowCredentials = "true" and origins = "*" to @CrossOrigin as,

@CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*")

You can change values of origins and allowedHeaders according to your requirements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM