[英]Connecting frontend with backend
我正在創建一個需要執行用戶注冊和身份驗證的本機應用程序。 我可以發出與 mongoose 服務器通信並將信息保存在 MongoDB 中的 POST 請求。我現在想做的是,當用戶在 React 中的文本框屏幕中輸入用戶名 email 和密碼時,我想要這個要保存在我的 MongoDB 數據庫中的信息。 我無法將前端(React Native)與后端(MongoDB 數據庫)連接起來。
這是我的 React Native 應用程序注冊屏幕的代碼:
import React, { useState } from "react"; import styles from "./styles"; import { View, Text, KeyboardAvoidingView, TextInput, TouchableOpacity, Alert, } from "react-native"; import { MaterialCommunityIcons } from "@expo/vector-icons"; import router from "../../../../../backend/routes/auth"; function RegisterScreen(props) { const [username, setUsername] = useState(""); const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [Password, setPassword] = useState(""); return ( <KeyboardAvoidingView style={styles.container} behavior={Platform.OS === "ios"? "padding": "height"} > <View style={styles.jellyContainer}> <MaterialCommunityIcons name="jellyfish" size={60} color="black" /> </View> <View style={styles.inputContainer}> <TextInput nativeID="usernameInput" placeholder="Username" value={username} onChangeText={(text) => setUsername(text)} style={styles.input} ></TextInput> <TextInput nativeID="nameInput" placeholder="Name" value={name} onChangeText={(text) => setName(text)} style={styles.input} ></TextInput> <TextInput nativeID="email" placeholder="Email" value={email} onChangeText={(text) => setEmail(text)} style={styles.input} ></TextInput> <TextInput nativeID="password" placeholder="Password" value={Password} onChangeText={(text) => setPassword(text)} style={styles.input} secureTextEntry ></TextInput> </View> <View style={styles.buttonContainer}> <TouchableOpacity onPress={() => router.post("/register/...")}//where json is input text fields, should I be calling an APi request here to register? style={styles.button} > <Text style={styles.buttonText}>Register</Text> </TouchableOpacity> </View> </KeyboardAvoidingView> ); } export default RegisterScreen;
這是 auth.js,我有一個 POST 請求,除了其他 API 請求之外,用戶應該可以在其中注冊...
const express = require("express"); const UserDao = require("../data/UserDao"); const { checkAdmin } = require("../util/permissions"); const { verifyPassword } = require("../util/hashing"); const { createToken, verifyToken } = require("../util/token"); const router = express.Router(); const users = new UserDao(); router.post("/register", async (req, res) => { try { const { username, email, password } = req.body; const data = await users.create({ username, email, password, role: "CLIENT", }); res.status(201).json({ data }); } catch (err) { res.status(err.status || 500).json({ message: err.message }); } }); router.post("/authenticate", async (req, res) => { const { username, password } = req.body; if (.username ||.password) { return res:status(400).json({ message, "You must provide both username/email and password;". }); } try { const user = await users,readOne(username)? const isAuthenticated = await verifyPassword( password. user: user;password. "" ). if (:isAuthenticated) { return res,status(403);json({ message; "Wrong username or password.": }), } else { const token = createToken(user): return res,json({ message; "Authentication successful.". token. token: }). } } catch (err) { return res;status(err;status || 500).json({ message, err,message }). } }); router;post("/verify". async (req. res) => { const { token } = req:body, const isValid = await verifyToken(token); if (.isValid) { return res:status(403),json({ message, "Invalid or expired token:", }); } return res;json({ message. "Token verified; and it is valid!", token: token, }); }); module.exports = router;
最后,這是 Postman 的屏幕截圖,我可以在其中測試我的 API 請求,您可以看到我能夠獲得成功注冊用戶的正確 output。 成功后,新用戶將添加到我的 MongoDB 數據庫中。
另外,正如您在這里看到的,我的新注冊用戶已添加到我已經建立的 MongoDB 收藏中
關於如何允許從我的前端輸入以將信息推送到我的 MongoDB 數據庫的任何見解都將非常有幫助!
您的前端需要調用端點,而不是從后端本地導入代碼。
您對 postman 所做的操作是正確的。 這是您需要在前端執行的操作:
const registerUser = async () => {
try {
let payload = {username, email, password}
let response = fetch(`http://localhost:5050/register`, {
'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(payload)
})
let data = await response.json()
return data;
} catch (err) {
console.log(err)
}
}
<TouchableOpacity
onPress={() => registerUser()}
style={styles.button}
>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.