我正在嘗試使用 Hooks 構(gòu)建一個 React 應(yīng)用程序,并使用 Node.js Express 服務(wù)器和 postgreSQL 數(shù)據(jù)庫。第一步是用戶注冊,但我在使用 axios 時遇到了一些奇怪的情況(還有可能相關(guān)或不相關(guān)的代理錯誤?)期望的行為:用戶填寫所有字段并單擊提交,數(shù)據(jù)發(fā)送到后端,存儲在數(shù)據(jù)庫中并分配用戶 ID,響應(yīng)返回到前端并且清除所有字段。如果用戶提交的信息不完整,則不會存儲該信息,并且后端的響應(yīng)會向用戶觸發(fā)一條錯誤消息。情況 1:用戶填寫所有字段。結(jié)果 1:行為符合預(yù)期,除了(a) 用戶數(shù)據(jù)也出現(xiàn)在搜索欄中,包括純文本的密碼,并且在保存數(shù)據(jù)后仍然存在,例如 http://localhost:3000/?first=Lucy&last=Who&email =who%40example.com&password=something#/(b) 以下錯誤:代理錯誤:無法將請求/注冊從 localhost:3000 代理到 http://localhost:5000/。有關(guān)更多信息,請參閱https://nodejs.org/api/errors.html#errors_common_system_errors (ECONNRESET)。[注意:我使用的是create-react-app,3000是開發(fā)服務(wù)器使用的端口,我的服務(wù)器使用5000]情況2: 用戶輸入的信息不完整,點擊提交。結(jié)果2:數(shù)據(jù)如上出現(xiàn)在搜索欄中,并發(fā)送到后端,輸入字段清晰,但顯然沒有返回任何響應(yīng),并且沒有觸發(fā)錯誤消息。情況2.1:用戶再次發(fā)送相同的不完整信息結(jié)果2.1:觸發(fā)錯誤消息。情況 2.2:用戶發(fā)送不同的不完整信息結(jié)果 2.2:錯誤消息清除。代碼 (抱歉,如果這太多/不夠,不確定問題出在哪里,使得弄清楚其他人可能需要知道的內(nèi)容變得有點棘手)注冊.jsserver.js(我認(rèn)為只是相關(guān)部分)app.post("/register", (req, res) => { console.log("/register route hit"); console.log("req body", req.body);const first_name = req.body.first;const last_name = req.body.last;const email = req.body.email;const password = req.body.password;let user_id;if (!first_name || !last_name || !email || !password) { res.json({ success: false, }); return;}hash(password).then((hashpass) => { db.addUser(first_name, last_name, email, hashpass) .then((results) => { console.log("results", results.rows[0]); user_id = results.rows[0].id; req.session.userId = user_id; res.json({ success: true }); }) .catch((err) => { console.log("err in addUser: ", err); res.json({ success: false }); }); return;});}); //end of register routeserver.listen(port, () => console.log(`listening on port ${port}`));最后,我從 axios.js 調(diào)用 axios:import axios from "axios";var instance = axios.create({xsrfCookieName: "mytoken",xsrfHeaderName: "csrf-token"});export default instance;
axios.post 在搜索欄中顯示用戶輸入
胡子哥哥
2023-11-12 21:53:09