简体   繁体   English

连接前端和后端

[英]Connecting frontend with backend

I am creating a react native app that needs to perform registering and authentication of users.我正在创建一个需要执行用户注册和身份验证的本机应用程序。 I am able to make a POST request that talks to a mongoose server and saves the information in MongoDB. What I want to do now is that when a user inputs their username, email, and password into a textbox screen in React, I want this informaiton to be savedin my MongoDB database.我可以发出与 mongoose 服务器通信并将信息保存在 MongoDB 中的 POST 请求。我现在想做的是,当用户在 React 中的文本框屏幕中输入用户名 email 和密码时,我想要这个要保存在我的 MongoDB 数据库中的信息。 I am having trouble connecting the frontend (React Native) with the backend (MongoDB database).我无法将前端(React Native)与后端(MongoDB 数据库)连接起来。

Here is the code for my register screen of my React Native App:这是我的 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;

Here is auth.js, where I have a POST request, where a user should be able to register, in addition to other API requests...这是 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;

Finally, here is a screenshot of Postman, where I am able to test my API requests and you can see that I am able to get the correct output back of a user being successfully registered.最后,这是 Postman 的屏幕截图,我可以在其中测试我的 API 请求,您可以看到我能够获得成功注册用户的正确 output。 Once this is successful, the new user is added to my MongoDB database.成功后,新用户将添加到我的 MongoDB 数据库中。

在此处输入图像描述

Also, as you can see here, my new registered user has been added to my already established MongoDB collection另外,正如您在这里看到的,我的新注册用户已添加到我已经建立的 MongoDB 收藏中

在此处输入图像描述

Any insight on how to allow input from my frontend to push information to my MongoDB database will be very helpful!关于如何允许从我的前端输入以将信息推送到我的 MongoDB 数据库的任何见解都将非常有帮助!

Your front end needs to be making a call to the endpoint, not locally import the code from your backend.您的前端需要调用端点,而不是从后端本地导入代码。

What you're doing with postman is correct.您对 postman 所做的操作是正确的。 Here is what you need to do in your front end:这是您需要在前端执行的操作:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM