reactjs 在React /Kotlin环境中配置CORS时出现问题

k5ifujac  于 2023-03-22  发布在  React
关注(0)|答案(1)|浏览(95)

我有一个react客户端试图调用一个用Kotlin和spring Boot 编写的API。在成功验证用户后,我试图获取一个用户列表,结果得到以下错误:

Access to fetch at 'http://localhost:8080/api/v1/demo-controller/users' from origin     
'http://localhost:3000' has been blocked by CORS policy: Response to preflight 
request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is 
present on the requested resource. If an opaque response serves your needs, set the 
request's mode to 'no-cors' to fetch the resource with CORS disabled.
main.c454458801d49c3baba9.hot-update.js:31          GET 
http://localhost:8080/api/v1/demo-controller/users net::ERR_FAILED
fetchUsers @ main.c454458801d49c3baba9.hot-update.js:31

这是我的后端配置bean:

@Bean
open fun corsConfigurationSource(): WebMvcConfigurer {
    return object : WebMvcConfigurer {
        override fun addCorsMappings(registry: org.springframework.web.servlet.config.annotation.CorsRegistry) {
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost:3000")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                    .allowedHeaders("*")
                    .allowCredentials(true)
                    .maxAge(3600)
        }
    }
}

这是我的控制器:

@RestController
@RequestMapping("/api/v1/demo-controller")
class DemoController(private val userService: UserService) {

@GetMapping("/users")
fun getAllUsers(): ResponseEntity<List<UserDTO>> {
    return ResponseEntity.ok(userService.getAllUsers())
}
}

这是我的react类:

const Home = () => {
const [users, setUsers] = React.useState([]);

const fetchUsers = async () => {
    const jwtToken = Cookies.get('jwtToken');

    const response = await fetch('http://localhost:8080/api/v1/demo-controller/users', {
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${jwtToken}`
        }
    });

    console.log(response);

    const content = await response.json();
    setUsers(content);
}

return (
    <div>
        <h1>Users:</h1>
        <button onClick={fetchUsers}>Fetch Users</button>
        <ul>
            {users.map((user: any) => (
                <li key={user.id}>{user.firstName} {user.lastName}</li>
            ))}
        </ul>
    </div>
);
};
export default Home;

我已经读了几篇关于CORS的文章,但我还没有能够破解这一个。

zazmityj

zazmityj1#

在Controller类中添加以下内容:

@org.springframework.web.bind.annotation.CrossOrigin("*")

相关问题