无法加载响应数据:未找到具有给定标识符的资源的数据

kaz*_*kaz 20 javascript reactjs axios

我正在 React 中制作注册表单并尝试使用 axios API 发送请求。我在代码中没有收到任何错误,但是当我单击注册按钮,然后转到控制台,然后转到网络时,我发现它无法加载响应数据。

我收到的错误是:

无法加载响应数据:未找到具有给定标识符的资源的数据

export class Register extends React.Component {

    handleSubmit = e => {
        e.preventDefault();
        const data = {
            first_name: this.firstName,
            last_name: this.lastName,
            email: this.email,
            password: this.password,
            password_confirm: this.confirmPassword
        };

        axios.post('http://localhost:8000/Register', data).then(
            res => {
                console.log(res)
            }
        ).catch(
            err => {
                console.log(err);
            }
        )
    };

    render() {
        return (
            <form onSubmit={this.handleSubmit} >
                <h3>Sign Up</h3>

                <div className="form-group">
                    <label> First Name</label>
                    <input type="text" className="form-control" placeholder="First Name"
                        onChange={e => this.firstName = e.target.value} />
                </div>

                <div className="form-group">
                    <label> Last Name</label>
                    <input type="text" className="form-control" placeholder="Last Name"
                        onChange={e => this.lastName = e.target.value} />
                </div>

                <div className="form-group">
                    <label> Email</label>
                    <input type="email" className="form-control" placeholder="Email"
                        onChange={e => this.email = e.target.value} />
                </div>

                <div className="form-group">
                    <label> Password</label>
                    <input type="password" className="form-control" placeholder="Password"
                        onChange={e => this.password = e.target.value} />
                </div>`

                <div className="form-group">
                    <label> Confirm Password</label>
                    <input type="password" className="form-control" placeholder="Confirm Password"
                        onChange={e => this.confirmPassword = e.target.value} />
                </div>`

                <button className="btn btn-primary btn-block" > Sign Up</button>

            </form >
        );

    }
}

export default Register;
Run Code Online (Sandbox Code Playgroud)

Lal*_*kya 2

更改后端服务器中的 cors 选项


当邮递员点击 API 时,即使 API 失败,它也会给你一个响应(500, 400, 401)。但是当从用户界面点击时,如果它给你空的响应。像下面这样在此输入图像描述

你需要这样做: 在前端,我使用的是Vite,所以端口号是5173。我必须在我的后端express服务器的cors选项中添加这个端口号。这为我解决了这个问题。希望这对您有帮助。

在此输入图像描述