Spring Boot:跨域策略缺少“access-control-allow-origin”。

3

错误:在Firefox中,我遇到了以下问题:外部站点查询被阻止:同源策略不允许读取远程资源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方法都出现了这个错误? - João Dias
1
我猜3000是前端应用程序运行的端口,8080是后端服务运行的端口。但我可能以错误的方式做出了这个假设。@WillGates,你能确认一下吗? - João Dias
我正在获取所有HTTP方法的内容。此外,我尝试了@CrossOrigin(origins = "*"),这应该适用于任何端口。 - WillGates
这是正确的 @JoãoDias - WillGates
如果省略@CrossOrigin,只有webconfig会发生什么? - Joker
显示剩余3条评论
1个回答

3

我刚刚注意到,您的依赖中有 Spring Security。 您可能忘记在您的 WebSecurityConfig 中启用 CORS。

例如,像这样:

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

我同意这似乎很可能是问题所在。有关此文档的参考,请参阅https://docs.spring.io/spring-security/site/docs/current/reference/html5/#cors - Stensig
啊,是的,那可能就是了。我现在不在家,但等我试一下,如果可以的话,我会把这个标记为解决方案!非常感谢你的帮助 :) ! - WillGates
成功了!我不再有CORS错误了,谢谢! - WillGates

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接