Spring Boot 使用 AJAX 请求和Sping Boot 获取CORS策略错误

s1ag04yj  于 2023-03-08  发布在  Spring
关注(0)|答案(1)|浏览(157)

下面是我 AJAX 请求:

$(document).on('click', '.internship-form-submit-btn', function(e) {
    e.preventDefault();
    var baseUrl = "localhost:8080/devhub";
    var formClass = $(this).closest('form').attr('class');
    var formSelector = $('.' + formClass);
    var formData = formSelector.serialize();
    var url = baseUrl + formSelector.data('action');

    $.ajax({
        type: 'POST',
        url: url,
        data: formData,
        success: function(response) {
          console.log(response);
        },
        error: function(xhr, status, error) {
          console.log('Error:', error);
        }
      });
})

Spring Boot中,我使用@CrossOrigin注解:

@RestController
@RequestMapping(value = "/internship")
@CrossOrigin ("*")
public class InternshipController {

    @PostMapping("/web-development")
    @ResponseBody
    public String postWebDevelopmentForm(@RequestBody WebDevelopmentDTO webDevelopmentDTO) {
        System.out.println("1");
        return "career-mentorship.html";
    }
}

但是在Chrome浏览器控制台上,我得到:

Access to XMLHttpRequest at 'localhost:8080/devhub/internship/web-development?firstName=&lastName=&email=&experience=&coverLetter=' from origin 'http://127.0.0.1:5501' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.

我参考了很多类似的帖子,但都没有帮助。我正在tomcat v9.0上运行我的应用程序

7gcisfzg

7gcisfzg1#

基本URL应以HTTP方案开头:

var baseUrl = "http://localhost:8080/devhub";

相关问题