来源已被CORS策略Spring boot and React阻止

问题描述 投票:0回答:2

带有React的Spring Boot

已被CORS策略阻止从来源[http://localhost:8080/”访问“ http://localhost:3000”处的XMLHttpRequest:

这是一个返回所有区域对象的控制器

已从CORS策略阻止从原点[http://localhost:8080/'访问'http://localhost:3000处XMLHttpRequest:在所请求的资源上没有'Access-Control-Allow-Origin'标头。

package com.ministry.demo.controller;

import com.ministry.demo.model.District;
import com.ministry.demo.repository.DistrictRepository;
import com.ministry.demo.service.DistrictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping(path = "district")
public class DistrictController {
    @Autowired
    DistrictService service;

    @GetMapping(path = "getAll")
    List<District> getAllDistrict(){
        return service.getAllDistricts();
    }
}
reactjs spring-boot controller cors-anywhere
2个回答
0
投票

如果后端和应用程序不在同一地址上运行,则浏览器通常不允许您调用后端。这旨在成为一项安全功能。

要允许浏览器调用api,请在后端响应中添加Access-Control-****标头(从Spring答复时)。

请参见https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

允许所有来源的最基本的标头:

Access-Control-Allow-Origin: *

这里是在Spring中添加这些标题的教程:https://spring.io/guides/gs/rest-service-cors/


0
投票

MyConfiguration.java

@Configuration
public class MyConfiguration implements WebMvcConfigurer {

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

}
© www.soinside.com 2019 - 2024. All rights reserved.