【问题标题】:Spring Boot: Cors policy missing 'access-control-allow-origin'Spring Boot:Cors 策略缺少“访问控制允许来源”
【发布时间】:2021-10-21 03:01:46
【问题描述】:

错误:我在 Firefox 中得到以下信息:Foreign Site Query Blocked:同源策略不允许读取远程资源 http://localhost:8080/api/v1/post/。 (原因:“Access-Control-Allow-Origin”CORS 标头不存在)

我花了几个小时来允许 CORS 与我的 Spring Boot 服务器通信,以使我的 REACT UI 与服务器通信。 Stack Overflow 上有很多类似措辞的问题,但建议的解决方案都没有解决我的问题...

Spring Boot 在https://spring.io/guides/gs/rest-service-cors/ 上提出了不同的解决方案。一种本地解决方案是使用注释。可以通过配置文件获得全局解决方案。

我已尝试使用 @CrossOrigin 注释控制器,如下面的代码所示:

package com.example.Blogging.api;

import com.example.Blogging.model.Post;
import com.example.Blogging.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.UUID;


@CrossOrigin(origins = "http://localhost:3000")
@RequestMapping("api/v1/post")
@RestController
public class PostController {

    private final PostService postService;

    @Autowired
    public PostController(PostService postService) {
        this.postService = postService;
    }


    @PostMapping
    public void addPost(@RequestBody Post post){
        postService.addPost(post);

    }

    @GetMapping
    public List<Post> getAllPosts(){
        return postService.getAllPosts();

    }

    @GetMapping(path = "{id}")
    public Optional<Post> getPostById(@PathVariable("id") UUID id){
        return postService.getPostById(id);

    }

    @PutMapping(path="{id}")
    public void updatePostById(@PathVariable("id") UUID id, @RequestBody Post post){
        postService.updatePost(id,post);
    }


    @DeleteMapping(path="{id}")
    public void deletePostById(@PathVariable("id") UUID id){
        postService.deletePost(id);
    }


}

这不起作用..我还尝试在每个方法而不是整个控制器类上进行注释。

此外,我尝试制作一个配置文件:

package com.example.Blogging.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
        .allowedOrigins("*");
    }
}

似乎没有任何效果。我浏览器中的控制台一直说响应标头中缺少“access-control-allow-origin”..

作为参考,我还将我的 pom.xml 放在下面:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>Blogging</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Blogging</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>



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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- SPRING SECURITY -->
        <!--<dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <scope>test</scope>
        </dependency>-->



        <!-- SPRING BOOT STARTER SECURITY -->
        <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

    </dependencies>

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

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.0.2</version>
            </plugin>

        </plugins>
    </build>

</project>

谁能提出解决方案?提前谢谢!

【问题讨论】:

  • 所有 HTTP 方法都出现此错误吗?
  • 只是一个评论,我在您的注释中看到您的PostController @CrossOrigin(origins = "http://localhost:3000") 端口 3000,而不是在您的文本中您提到端口 8080。可能是您在端口中有错字,这就是原因不工作?
  • 我猜 3000 是 Frontend App 运行的地方,8080 是 Backend 服务所在的地方。但我可能以错误的方式假设这一点。你能确认一下@WillGates 吗?
  • 我正在为所有 HTTP 方法获取它是的。我还尝试了@CrossOrigin(origins = "*"),它应该适用于任何端口
  • 没错@JoãoDias

标签: java spring spring-boot spring-mvc axios


【解决方案1】:

我刚刚注意到,您的依赖项中有 Spring Security。 您可能错过了在 WebSecurityConfig 中启用 CORS。

例如。像这样:

@EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().and()...
        }
    }

【讨论】:

  • 我同意这似乎是问题所在。有关这方面的文档参考,请参阅docs.spring.io/spring-security/site/docs/current/reference/…
  • 啊,是的,大概就是这样。我目前不在家,但是当我尝试它时,如果它有效,我会将其标记为解决方案!非常感谢您的帮助:)!
  • 成功了!我没有 CORS 错误了,谢谢!
猜你喜欢
  • 2021-05-30
  • 2019-12-18
  • 2018-07-07
  • 2020-06-06
  • 2021-11-03
  • 2016-09-08
  • 2016-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多