Java 对Spring引导应用程序使用AJAX请求时在Chrome中获取CORS错误

Java 对Spring引导应用程序使用AJAX请求时在Chrome中获取CORS错误,java,jquery,ajax,spring,maven,Java,Jquery,Ajax,Spring,Maven,我试图在本地运行Spring Boot应用程序,但在向应用程序发出AJAX请求时遇到了一些问题。Chrome给了我以下错误(实际上来自jquery): 我正在尝试通过以下方法处理POST请求。这实际上对邮递员有效 @RequestMapping(value = "/api/input", method = RequestMethod.POST) public @ResponseBody UserInputModel getUserInput(@RequestBody UserInputModel

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

我正在尝试通过以下方法处理POST请求。这实际上对邮递员有效

@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>
my.group
appname
0.0.1-快照
罐子
appname
SpringBoot的演示项目
org.springframework.boot
spring启动程序父级
1.5.8.1发布
UTF-8
UTF-8
1.8
org.springframework.boot
SpringBootStarterWeb
mysql
mysql连接器java
运行时
org.springframework.boot
弹簧起动试验
测试
org.springframework.boot
springbootmaven插件
真的
您可以使用JSONP:

或者,您可以在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);
    }
}

签出:

尝试使用url:“/api/input”“没有充分的理由path@vratojr你应该得到一个大大的吻。但这究竟是为什么起作用?@Xzenon只有当API与您发送http请求的客户端位于同一主机上时,它才起作用。阅读CORS。我不确定:)这是我经历过的事情,我认为把完整的地址解释为浏览器愿意做一个跨来源的请求。如果你没有指定地址,这意味着你使用的是好的地址,而不是做坏事。这个web应用程序是由spring boot应用程序交付的吗?如果不是,您能否确保它始终与api服务器来自同一主机?如果没有,您必须在spring boot应用程序中启用CORS。检查一下
@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);
    }
}