javascript 从react客户端向node.js服务器端发送表单数据

kx5bkwkv  于 2023-01-01  发布在  Java
关注(0)|答案(2)|浏览(147)

我在客户端有一个登录表单(react),我尝试提交该表单并将凭据传递给服务器端的登录函数(node.js)
当我使用postman发送带有用户名和密码的原始json对象时,它工作正常,但是当我通过客户端发送它时,req.body只包含以下内容:原型:对象
我到底做错了什么?

以下是包含表单的组件的代码:

import React from 'react';
import '../signIn/signIn.component.css'
import { Link } from "react-router-dom";
import { useState, useEffect } from "react";

export default function SignIn() {
    const [UserName, setUsername] = useState(null);
    const [PassWord, setPassWord] = useState(null);
    const [FormData, setFormData] = useState({});

    useEffect(() => {
        setFormData({ UserName: UserName, PassWord: PassWord });
    }, []);

    const submitFormSignIn = () => {
        const testURL = "http://localhost:3100/login";
        const myInit = {
            method: "POST",
            mode: 'no-cors',
            body: JSON.stringify(FormData),
            headers: {
                'Content-Type': 'application/json'
            },
        };
        const myRequest = new Request(testURL, myInit);
        fetch(myRequest).then(function (response) {
            return response;
        }).then(function (response) {
            console.log(response);
        }).catch(function (e) {
            console.log(e);
        });
    }

    return (
        <React.Fragment>
            <form onSubmit={(e) => { submitFormSignIn(); e.preventDefault(); }}>
                <div className="signIn-form-container">
                    <h1 className="welcome-header">Welcome</h1>
                    <div className="userName-form-container">
                        <input className="input-user-name" type="text" name="userName" placeholder='User name'
                            //should start with an alphabet so. All other characters can be alphabets, numbers or an underscore so.
                            required
                            pattern="^[A-Za-z][A-Za-z0-9_]{7,29}$"
                            minLength={"6"}
                            maxLength={"20"}
                            onChange={(e) => setUsername(e.target.value)}
                        ></input>
                    </div>
                    <div className="password-form-container">
                        <input className="input-password" type="password" name="passWord" required
                            //Minimum eight characters, at least one uppercase letter, one lowercase letter and one number:
                            pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$"
                            autoComplete="on"
                            minLength={"9"}
                            maxLength={"20"}
                            placeholder='Password'
                            onChange={(e) => setPassWord(e.target.value)}
                        ></input>
                    </div>
                    <div className="forgot-remember-container">
                        <Link className="userName-forgot-link" to="/userNameRecovery">Forgot user name?</Link>
                        <Link className="password-forgot-link" to="/passwordRecovery">Forgot password?</Link>
                    </div>
                    <div className="form-submit-btn-container">
                        <button className="form-submit-btn">Sign in</button>
                    </div>
                    <div className="sign-up-container">
                        <a>Don't have an account?</a>
                        <Link className="signUp-link" to="/register">Sign up</Link>
                    </div>
                    <hr></hr>
                </div>
            </form>
        </React.Fragment>
    );
}
l0oc07j2

l0oc07j21#

你的useEffect只被触发一次--在初始渲染之后,因为它的dependency数组是空的。这意味着,你没有为formData状态设置正确的数据。
我认为有两种解决办法:用UserNamePassWord状态填充依赖关系数组:

useEffect(() => {
        setFormData({ UserName: UserName, PassWord: PassWord });
    }, [UserName, PassWord]);

或者--我建议这样做--直接从用户名和密码状态轻松创建body对象,以便:

body: JSON.stringify({UserName, PassWord}),

小下划线提示:状态是变量,所以它们的名字应该是camelCase,并且以小写开头。2大写的变量应该是React组件。

2ic8powd

2ic8powd2#

在本例中,useEffect是绝对不必要的,因为您同时拥有submit处理程序和useEffect,它们实际上会使应用程序通过setState重新呈现几次,所以我将构建类似的内容

import React from 'react';
import '../signIn/signIn.component.css'
import { Link } from "react-router-dom";
import { useState } from "react";

export default function SignIn() {
    const [username, setUsername] = useState(null);
    const [password, setPassword] = useState(null);

    const submitFormSignIn = () => {
        const testURL = "http://localhost:3100/login";
        const myInit = {
            method: "POST",
            mode: 'no-cors',
            body: JSON.stringify({ username, password }),
            headers: {
                'Content-Type': 'application/json'
            },
        };
        const myRequest = new Request(testURL, myInit);
        fetch(myRequest).then(function (response) {
            return response;
        }).then(function (response) {
            console.log(response);
        }).catch(function (e) {
            console.log(e);
        });
    }

    return (
        <React.Fragment>
            //same jsx
        </React.Fragment>
    );
}

相关问题