【问题标题】:Getting CORS error in Chrome when using AJAX requests to a Spring Boot application对 Spring Boot 应用程序使用 AJAX 请求时在 Chrome 中出现 CORS 错误
【发布时间】:2017-11-30 13:41:36
【问题描述】:

我正在尝试在本地运行 Spring Boot 应用程序,但在向应用程序发送 AJAX 请求时遇到了一些问题。 Chrome 给了我以下错误(实际上来自 jquery):

Failed to load localhost:8080/api/input: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

我正在尝试发出将由以下方法处理的 POST 请求。这实际上适用于 Postman。

@RequestMapping(value = "/api/input", method = RequestMethod.POST)
public @ResponseBody UserInputModel getUserInput(@RequestBody UserInputModel input)
{
    input.setMessage("bye");

    return input;
}

这是发出请求的脚本:

$(document).ready(function () {
$('#submitInput').click(function () {

    // Only send the message to the server if the user typed something
    var userMessage = {
        message: $('#userInput').val()
    };

    console.log(userMessage);

    if (userMessage.message) {
        console.log("Sending request");
        $.ajax({
            url: "localhost:8080/api/input",
            dataType: "json",
            contentType: "application/json; charset=UTF-8",
            data: JSON.stringify(userMessage),
            type: 'POST',
            success: function() {
                console.log("yay");
            },
            error: function(err) {
                console.log(err);
            }
        });
    } else {
        console.log("Empty input, no request sent");
    }
});

console.log("Loaded testScript.js");
});

这就是有效的方法。我有另一个控制器返回一个 html 页面(它也加载我的脚本)。这在 Chrome 中确实有效,我得到了带有文本框和按钮的页面,并且确实加载了脚本。问题是从脚本返回到应用程序的请求不起作用。

这是 pom.xml:

<?xml version="1.0" encoding="UTF-8"?>

http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0

<groupId>my.group</groupId>
<artifactId>appname</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>appname</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <addResources>true</addResources>
            </configuration>
        </plugin>
    </plugins>
</build>

【问题讨论】:

  • 尝试使用没有完整路径的 url: "/api/input"
  • @vratojr 你应该得到一个大大的吻。但究竟为什么这行得通?
  • @Xzenon 仅当 API 与您发送 http 请求的客户端位于同一主机上时才有效。阅读 CORS。
  • 我不确定 :) 这是我经历过的事情,我认为放置完整地址被浏览器解释为执行跨源请求的意愿。如果您不指定地址,则表示您使用的是 GOOD 并且您没有尝试做坏事。
  • web 应用是spring boot 应用交付的吗?如果不是,你能确定它总是来自与 api 服务器相同的主机吗?如果没有,您必须在您的 Spring Boot 应用程序中启用 CORS。检查spring.io/guides/gs/rest-service-cors

标签: java jquery ajax spring maven


【解决方案1】:

您可以使用 JSONP:https://dev.socrata.com/docs/cors-and-jsonp.html

或者您可以在 Spring boot 中指定显式配置:

@Configuration
public class RestConfig {
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("DELETE");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

签出:How to configure CORS in a Spring Boot + Spring Security application?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-03
    • 2021-01-27
    • 2019-07-05
    • 2021-11-16
    • 2021-08-01
    • 2020-11-29
    • 2017-04-03
    相关资源
    最近更新 更多