axios.post do not return anything when api call is made within backend

29 views Asked by At

I'm setting up a account validation page with the following approach. An apiGateway.ts where the request from POSTMAN or UI would hit. The backend is setup at localhost:3001 and here is the code of apiGateway.ts, you can ignore the login methods using fetch, my interest is register here.

import express from "express";
import cors from "cors";
import carRouter from "./Car/Router";
import reservationRouter from "./Reservation/Router";
import userRouter from "./User/Router";
import axios from "axios";

const BASE_RENTAL_URL = "http://localhost:3001/user";
const app = express();
app.use(cors());
app.use(express.json());

app.use("/rentals", carRouter);
app.use("/mybookings", reservationRouter);
app.use("/user", userRouter);

app.post("/login", async (req, res) => {
  try {
    const { email, mobile, password } = req.body;
    let fetchUserToken;
    if (mobile) {
      fetchUserToken = await fetch(BASE_RENTAL_URL + `/mobilelogin`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ mobile: mobile }),
      });
    } else {
      fetchUserToken = await fetch(BASE_RENTAL_URL + `/emaillogin`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ email: email, password: password }),
      });
    }
    const token = fetchUserToken?.json();
    res.status(200).json({ token });
  } catch (error: any) {
    res.status(500).json({ message: error.message });
  }
});

app.post("/register", async (req, res) => {
  try {
    const response = await axios.post(
      "http://localhost:3001/user/register",
      req.body
    );
    console.log("got it", response.data);
    res.status(200).json({ token: response.data });
  } catch (error: any) {
    console.log("hello", error.message);
    res.status(500).json({ message: error.message });
  }
});

axios.interceptors.request.use((request) => {
  console.log("Request URL:", request.url);
  return request;
});

export default app;

Here is the code for the User router.ts

import express from "express";
import Controller from "./Controller";

const router = express.Router();

export default () => {
    router.get("/user", Controller.findAllUsers);
    router.post("/user/mobilelogin", Controller.handleLoginThroughMobile);
    router.post("/user/emaillogin", Controller.handleLoginThroughEmail);
    router.post("/user/register", Controller.handleRegistration);
    return router;
}

and here is the Controller.ts for User

import { Request, Response } from "express";
import Repository from "./Repository";
const bcrypt = require("bcrypt");
const jwt = require('jsonwebtoken');

class Controller {

  async findAllUsers(req: Request, res: Response, next: any) {
    try {
      const users = await Repository.findAll();
      res.status(200).json(users);
    } catch (error: any) {
      res.status(500).json({ message: error.message });
    }
  }

  async handleLoginThroughMobile(req: Request, res: Response, next: any) {
    try {
      const { mobile } = req.body;
      let user = await Repository.findUserByMobile(mobile);
      if (!user) {
        res.status(401).json({ message: "User doesn't exist" });
        return;
      }
      const token = jwt.sign({ email: user[0].email }, 'secret', { expiresIn: '1h' });
      res.status(200).json({ token });
    } catch (error: any) {
      res.status(500).json({ message: error.message });
    }
  }

  async handleLoginThroughEmail(req: Request, res: Response, next: any) {
    try {
      const { email, password } = req.body;
      let user = await Repository.findUserByEmail(email);
      if (!user) {
        res.status(401).json({ message: "User doesn't exist" });
        return;
      }
      const isValidPassword = await bcrypt.compare(password, user[0].password);
      if (!isValidPassword) {
        res
          .status(401)
          .json({ message: "Credentials are not correct. Try again" });
        return;
      }
      const token = jwt.sign({ email: user[0].email }, 'secret', { expiresIn: '1h' });
      res.status(200).json({ token });
    } catch (error: any) {
      res.status(500).json({ message: error.message });
    }
  }

  async handleRegistration(req: Request, res: Response, next: any) {
    try {
      console.log("hits");
      const { email, mobile, licenseNumber } = req.body;
      let userWithSameEmail = await Repository.findUserByEmail(email);
      let userWithSameMobile = await Repository.findUserByMobile(mobile);
      let userWithSameLicenseNumber = await Repository.findUserByLicenseNumber(
        licenseNumber
      );
      if (
        userWithSameEmail ||
        userWithSameMobile ||
        userWithSameLicenseNumber
      ) {
        res.status(401).json({
          message: "User with same email or mobile or license number exists",
        });
        return;
      }
      const user = await Repository.create(req.body);
      const token = jwt.sign({ email: user.email }, 'secret', { expiresIn: '1h' });
      res.status(200).json({ token });
    } catch (error: any) {
      console.log("error", error);
      res.status(500).json({ message: error.message });
    }
  }
}

export default new Controller();

Please let me know why am I not able to get the token or any response for that matter when I make a request from POSTMAN to 'http://localhost:3001/register'. My understanding is that when i hit 'http://localhost:3001/register' from POSTMAN, it would trigger the api.post('register') defined in apiGateway.ts, and then it further makes a call to 'http://localhost:3001/user/register' and this should trigger the Controller method for handling Registration. But I don't see the flow hitting the controller, and the postman request neither returns success or is failed.

0

There are 0 answers