我正在嘗試使用 Hooks 構建一個 React 應用程序,并使用 Node.js Express 服務器和 postgreSQL 數據庫。第一步是用戶注冊,但我在使用 axios 時遇到了一些奇怪的情況(還有可能相關或不相關的代理錯誤?)期望的行為:用戶填寫所有字段并單擊提交,數據發送到后端,存儲在數據庫中并分配用戶 ID,響應返回到前端并且清除所有字段。如果用戶提交的信息不完整,則不會存儲該信息,并且后端的響應會向用戶觸發一條錯誤消息。情況 1:用戶填寫所有字段。結果 1:行為符合預期,除了(a) 用戶數據也出現在搜索欄中,包括純文本的密碼,并且在保存數據后仍然存在,例如 http://localhost:3000/?first=Lucy&last=Who&email =who%40example.com&password=something#/(b) 以下錯誤:代理錯誤:無法將請求/注冊從 localhost:3000 代理到 http://localhost:5000/。有關更多信息,請參閱https://nodejs.org/api/errors.html#errors_common_system_errors (ECONNRESET)。[注意:我使用的是create-react-app,3000是開發服務器使用的端口,我的服務器使用5000]情況2: 用戶輸入的信息不完整,點擊提交。結果2:數據如上出現在搜索欄中,并發送到后端,輸入字段清晰,但顯然沒有返回任何響應,并且沒有觸發錯誤消息。情況2.1:用戶再次發送相同的不完整信息結果2.1:觸發錯誤消息。情況 2.2:用戶發送不同的不完整信息結果 2.2:錯誤消息清除。代碼 (抱歉,如果這太多/不夠,不確定問題出在哪里,使得弄清楚其他人可能需要知道的內容變得有點棘手)注冊.jsserver.js(我認為只是相關部分)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 調用 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