Frogical
Frogical

Reputation: 185

How can I handle data/json that I retrieve from my API Webservice (ExpressJS)?

I'm new to NodeJS and ExpressJS. I created an AuthController which handles the login post.

exports.login = async (req, res, next) => {
try {
    const email = req.body.email;
    const password = req.body.password;

    const user = await User.findOne({ email }).select("+password");
    if (!user) {
        const error = new Error("Wrong Credentials");
        error.statusCode = 401;
        throw error;            
    }

    const validPassword = await user.validPassword(password);
    if (!validPassword) {
        const error = new Error("Wrong Credentials");
        error.statusCode = 401;
        throw error;      
    }

    const token = jwt.encode({id: user.id}, config.jwtSecret);
    res.send({user, token});
} catch(err) {
    next(err);
}
}

I would like to use this method in my web application to let the user login. If the user succesfully logs in, I get a json response in my browser with the user and the token. That's not what I want. The url for the api login is: /api/auth/login. I created a function in my web application:

router.post('/login', async (req, res, next) => {
    var apiResponse = await authController.login(req, res, next);
    res.render('profile.ejs', {user: apiResponse.user});
});

I keep getting the error that authController.login is not a function. My question is how can I use the method from my API and use the response in my webapplication? Can someone help me out?

Upvotes: 0

Views: 53

Answers (1)

Titus Sutio Fanpula
Titus Sutio Fanpula

Reputation: 3613

You can do it like this code below: 👇

router.post('/login', authController.login, async (req, res, next) => {
    res.render('profile.ejs', {user: apiResponse.user});
});

👨‍🏫 Please read the documentation about Express Middleware.

Updated: Middleware

Make sure your authController looks like this code below:

exports.login = async (req, res, next) => {
  try {
      const email = req.body.email;
      const password = req.body.password;

      const user = await User.findOne({ email }).select("+password");
      if (!user) {
          const error = new Error("Wrong Credentials");
          error.statusCode = 401;
          throw error;            
      }

      const validPassword = await user.validPassword(password);
      if (!validPassword) {
          const error = new Error("Wrong Credentials");
          error.statusCode = 401;
          throw error;      
      }

      const token = jwt.encode({id: user.id}, config.jwtSecret);
      // passing your data to next function
      // you can change exampleData with the 'variable' you want
      req.exampleData = { user, token }
      next();
  } catch(err) {
      next(err);
  }
}

If your authController is same root ("folder") with the your routes, than make it's look like this:

const { login } = require('./authController');

So, now, you can call the authController like this:

router.post('/login', login, async (req, res, next) => {
  // your data: "user" and "token" from middleware
  const { exampleData } = req;
  console.log(exampleData);
  res.render('profile.ejs', {user: exampleData});
});

I hope it's can help you 🙏.

Upvotes: 1

Related Questions