我在客戶端(反應)有一個登錄表單,我嘗試提交并將憑據傳遞給服務器端的登錄功能(node.js)
當我使用郵遞員發送帶有用戶名和密碼的原始 json 物件時,它作業正常,但是當我通過客戶端發送它時,req.body 僅包含以下內容:[[Prototype]]: Object
我在這里做錯了什么?
這是包含表單的組件的代碼:
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>
);
}
uj5u.com熱心網友回復:
您的 useEffect 僅觸發一次 - 在初始渲染后,因為它的依賴陣列為空。這意味著,您沒有使用適當的資料設定 formData 狀態。
UserName我看到了兩個解決方案:要么用和PassWord狀態填充依賴陣列:
useEffect(() => {
setFormData({ UserName: UserName, PassWord: PassWord });
}, [UserName, PassWord]);
或者 - 我會推薦這個 - 直接從 UserName 和 PassWord 狀態輕松創建您的主體物件:
body: JSON.stringify({UserName, PassWord}),
小下劃線注意:狀態是變數,所以它們的名字應該是camelCase,以小寫開頭。帶有大寫字母的變數旨在成為 React 組件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/495147.html
標籤:javascript 节点.js 反应 形式 获取 API
