Home > OS >  Connecting frontend with backend
Connecting frontend with backend

Time:02-27

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. I am having trouble connecting the frontend (React Native) with the backend (MongoDB database).

Here is the code for my register screen of my React Native App:

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...

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. Once this is successful, the new user is added to my MongoDB database.

enter image description here

Also, as you can see here, my new registered user has been added to my already established MongoDB collection

enter image description here

Any insight on how to allow input from my frontend to push information to my MongoDB database will be very helpful!

CodePudding user response:

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. 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}
>
  • Related