【问题标题】:React POST request to java spring rest API cors error将 POST 请求反应到 java spring rest API cors 错误
【发布时间】:2022-01-25 01:39:15
【问题描述】:

所以我正在努力建立一个带有 java spring 后端的全栈应用程序的基础,最终是一个 mysql 数据库和一个 react 前端。我目前可以使用以下代码将我的后端“用户”存储库发送到反应前端

用户类别:

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    
    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    private String email;

    public User(){
    }
    public User(String firstName, String lastName, String email){
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

    
}

用户休息控制器:

CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("api/")
public class UserController {
    
    @Autowired
    private UserRepository userRepository;

    @GetMapping("users")
public List<User> getUsers(){
    return this.userRepository.findAll();
}

@RequestMapping(method=RequestMethod.POST, value="/signin")
public void login(@RequestBody User user) { 
System.out.println(user);
   }
}

在后端存储库中,我创建了三个假用户,并在 react 中显示它们:

import react from "react";
import UserService from "../services/UserService";

class UserComponent extends react.Component {

    constructor(props){
        super(props);
        this.state = {
            users:[]
        }
    }

    componentDidMount(){
        UserService.getUsers().then((response) => {
            this.setState({users: response.data})
        });
    }

    sendUsers(){
        return this.state;
    }

    render (){
        return (
            <div>
                <h1 className = "text-center">Users List</h1>
                <table className = "table table-striped">
                    <thead>
                        <tr>
                            <td> User Id</td>
                            <td> User First Name</td>
                            <td> User Last Name</td>
                            <td> User Email</td>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            this.state.users.map(
                                user =>
                                <tr key= {user.id}>
                                    <td> {user.id}</td>
                                    <td> {user.firstName}</td>
                                    <td> {user.lastName}</td>
                                    <td> {user.email}</td>
                                </tr>
                            )
                        }
                    </tbody>
                </table>
            </div>
        )
    }
}

export default UserComponent

这一切都很好,直到我尝试将用户名和密码发送回我的 java spring rest api,我是全栈开发的新手,我确定我在做的是一个基本错误。这是我的代码,其中 getUsers() 函数有效,而 login() 函数无效

import axios from "axios";
import authHeader from "./auth-header";

const USERS_REST_API_URL = 'http://localhost:8080/api/users';
const API_URL = 'http://localhost:8080/api';

class UserService{
    login(username, password) {
        console.log(username);
        console.log(password);
        return axios
          .post(API_URL + "/signin", {
            username,
            password
          })
          .then(response => {
            if (response.data.accessToken) {
              localStorage.setItem("user", JSON.stringify(response.data));
            }
    
            return response.data;
          });
      }

    getUsers(){
        console.log(USERS_REST_API_URL);
        return axios.get(USERS_REST_API_URL);
    }
    
    getPublicContent() {
    return axios.get(API_URL + 'all');
  }

  getUserBoard() {
    return axios.get(API_URL + 'user', { headers: authHeader() });
  }

  getModeratorBoard() {
    return axios.get(API_URL + 'mod', { headers: authHeader() });
  }

  getAdminBoard() {
    return axios.get(API_URL + 'admin', { headers: authHeader() });
  }
}

export default new UserService();

如您所见,我正在将有效的用户名和密码发布到“http://localhost:8080/api/signin”,并遇到以下错误 “从源 'http://localhost:3000' 访问 XMLHttpRequest 在 'http://localhost:8080/api/signin' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否'请求的资源上存在 Access-Control-Allow-Origin' 标头。"

您可以在我的休息控制器中的第二个代码段的顶部看到我允许来自 localhost:3000 的跨域,并且我能够在我的反应前端很好地接收用户数据,任何关于是什么原因的想法这个错误?谢谢

【问题讨论】:

  • 确保您在 cors 配置中设置了 allow-credentials="true"

标签: java reactjs spring rest


【解决方案1】:

正是我之前遇到的问题,你可以看任何文章here

简而言之(见最后一节),

...浏览器有一个“同源策略”,可以被称为 CORS(跨源资源共享)的东西覆盖...您可以允许 localhost:3000 作为“允许的来源”,这样它就不会被浏览器屏蔽了。

@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:3000");
            }
        };
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-03
    • 2018-02-03
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    相关资源
    最近更新 更多