简体   繁体   English

在对Spring Boot应用程序使用AJAX请求时,在Chrome中出现CORS错误

[英]Getting CORS error in Chrome when using AJAX requests to a Spring Boot application

I am trying to run a Spring Boot application locally and I have some issues making an AJAX request back to the app. 我试图在本地运行一个Spring Boot应用程序,并且我有一些问题将AJAX请求发回给应用程序。 Chrome gives me the following error (which is actually from jquery): Chrome给了我以下错误(实际上是来自jquery):

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

I am trying to make a POST request that will be handled by the following method. 我正在尝试发出一个POST请求,该请求将由以下方法处理。 This actually works with Postman. 这实际上适用于Postman。

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

    return input;
}

Here's the script that's making the request: 这是发出请求的脚本:

$(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");
});

So here's what's working. 所以这就是有效的。 I have another controller that returns an html page (which also loads my script). 我有另一个控制器返回一个html页面(也加载我的脚本)。 This does work in Chrome, I get my page with the textbox and button and the script is indeed loaded. 这在Chrome中有效,我使用文本框和按钮获取我的页面,并且脚本确实已加载。 The problem is that the request from the script back to the app is not working. 问题是脚本返回应用程序的请求不起作用。

Here's the pom.xml: 这是pom.xml:

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

http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 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>

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

Or you can specify an explicit config in Spring boot: 或者您可以在Spring启动中指定显式配置:

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

Check out: How to configure CORS in a Spring Boot + Spring Security application? 查看: 如何在Spring Boot + Spring Security应用程序中配置CORS?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 POST 请求时 Spring Boot 安全性和 CORS 的问题 - Problem with Spring Boot Security and CORS when it comes to POST requests 在Spring Box应用程序的Virtual Box上运行WAR时出现错误 - Getting Error when running WAR on Virtual Box for Spring Boot Application 将本地 React 前端连接到本地 Spring Boot 中间件应用程序时出现 CORS 错误 - CORS error when connecting local React frontend to local Spring Boot middleware application 错误 CORS Forbidden 403 Spring Boot With Spring Security when using Path Variable - Error CORS Forbidden 403 Spring Boot With Spring Security when using Path Variable StormPath Spring Boot集成-收到无效的CORS请求错误 - StormPath Spring Boot Integration - getting Invalid CORS request error Spring Boot CORS 阻止 DELETE 请求 - Spring Boot CORS blocks DELETE requests 在 Spring 引导应用程序中出现 MySQL 语法错误 - Getting MySQL syntax error in Spring Boot Application 使用 Spring Boot + REST 应用程序出现 404 错误 - Getting 404 error with Spring Boot + REST application 使用 nginx 在 Spring Boot 中代理 websockets 时出现 CORS 错误 - CORS error when proxying websockets in spring boot with nginx 当我运行 Spring 引导应用程序时,我收到以下错误。 我正在使用 spring 启动版本 2.3.1 - When I am running my Spring Boot application, I am getting the below error. I am using spring boot version 2.3.1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM