Calling external api endpoints when working with node and ejs and geting the details for your users

丶灬走出姿态 提交于 2021-02-11 07:28:09

问题


i have a signup and login form,am using ejs to render as view, i have been given some api endpoint to call, and i have added them to their ejs form action views when i fill in the user details in my ejs view form i get this response.

i get this when am trying to register a user

    {
      "status": 200,
      "message": "Account created successfully.",
      "data": {
        "name": "name of user",
        "email": "user email",
        "password": "$2b$10$0IPgBNCJhjjkasdkGb2y0CviOuxRe/bAfhFqFDqrofMaCz5f0SMtwkgBxIzm"
      }
    }

i get this when am trying to login a registered user

{
  "status": 200,
  "message": "Account logged in successfully.",
  "data": [
    {
      "id": 9,
      "name": "username",
      "email": "useremail@gmail.com",
      "password": "$2b$10$v3/zhn0pP6BMaTlfcoaMUuMlaHPGht6v2sf03e6uB3OPIQ3ggdpdi",
      "date_created": "2020-02-21T13:15:33.000Z"
    }
  ]
}

i get this when i post the sign in form with the details of an already registered user

    {
      "status": 400,
      "message": "Provided email address already exists, try another",
      "data": null
    }

i get this when am trying to login with bad credentials

    {
      "status": 400,
      "message": "Incorrect password provided, try again.",
      "data": null
    }

please my question is how do i have access to this details so i can send them to the client in my ejs view


回答1:


you can use the npm package request, so you install it with this npm i request now you will need one function that you will always call whenever you want to use the api endpoint


    var request = require("request");

    module.exports = {

        // DATA IN { name: 'aaa', email: 'pass@gmail.com', password: '123' } FORMAT
        callAPI:function(url, data, callback){

            var options = { method: 'POST',
            url: url,
            headers: 
            {
                'cache-control': 'no-cache',
                'content-type': 'application/json'
            },
            body: data,
            json: true };

            request(options, function (error, response, result) {
            if (error){
                return callback(error);
            }else{
                callback(null, result);  
            };

            });

        }

    }

and you can use this as an example to call the function


    app.post('/signup', function (req, res) {
            var data = {
                "name": req.body.name,
                "email": req.body.email,
                "password": req.body.password
            }

            functions.callAPI("https://api/endpoin/signup", data, function (error, result) {
                if (error) {
                    var response = {
                        "status": 400,
                        "message": error,
                        "data": null
                    }
                    res.render('signup', {response: response});
                } else {
                    var response = result;
                    if (response.status === 400) {
                        res.render('signup', {response: response});
                    } else {
                        res.redirect('/login');
                    }
                }
            });


        });




回答2:


First step install axios (npm i axios )

In folder(controllers/authController.js),write this code

require('dotenv').config()
const request = require('request')
const axios = require('axios')
const createErrors = require('http-errors')
module.exports = {
    callAPI: function(url, body, callback) {

    axios.post(process.env.BASE_URL, body, {
            headers: {
                'cache-control': 'no-cache',
                'Authorization': 'Token token=\"1234455433222222\"',
                'Content-Type': 'application/json'
            },
        })
        .then(function(response) {
            console.log(response, "istheresponse");
            callback(null, response)
        })
        .catch(function(error) {
            if (error.response) {
                callback(error.response)
                    // Request made and server responded
                console.log(error.response.data);
                console.log(error.response.status);
                console.log(error.response.headers);
            } else if (error.request) {
                callback(error.request)
                    // The request was made but no response was received
                console.log(error.request);
            } else {
                callback(error.message)
                    // Something happened in setting up the request that triggered an Error
                console.log('Error', error.message);
            }
        });
   }

}

Now,create routes folder (routes/Auth.routes.js)

    require('dotenv').config()
const express = require('express')
const router = express.Router()
const axios = require('axios')
const authController = require('../controllers/Auth.controllers')


  
router.get('/', (req, res, next) => {
    res.render('pages/auth/index')
})


router.get('/signin', (req, res, next) => {
    res.render('pages/auth/signin', { title: 'website-name | Signin', value: 'Signin' })
})
 
router.post('/signin/', function(req, res) {
    var data = {
        
            "name": req.body.username,
            "email": req.body.email,
            "password": req.body.password,
            
    }
    console.log(data)
    authController.callAPI(process.env.BASE_URL, data, function(error, result) {
        if (error) {
            var response = {
                "status": 400,
                "message": error, 
            }
            res.render('pages/auth/signin', { response: result });
            console.log(error)
} else {
        // console.log(error, ' is the error');
        // console.log(result, 'is the result')

        if (result.data.status == 200) {
            res.redirect('/');
        } else {
            res.render('pages/auth/signin', { response: result, title: 'website-name | Signin', value: 'Signin' });
        }         
    }



  });
});

module.exports = router

In (pages/auth/signin.ejs) folder

    <form id="signin" name="signin" class="default-form" action="/signin" method="post">

                <div class="login-form">
                    <div class="sign-in-htm">
                        <div class="group">
                            <input id="user" type="text" name="name" class="input" placeholder="name">
                        </div>
                        <div class="group">
                             
                            <input id="pass" type="password" name="password" class="input" data-type="password" placeholder="Password">
                        </div>
                        <div class="group">                            
                        <input id="pass" type="email" name="email" class="input" data-type="email" placeholder="email">
                        </div>
                        <div class="group">
              
                            <button type="submit" value="submit" class="button">Login</button>
                        </div>
            </form>


来源:https://stackoverflow.com/questions/60340027/calling-external-api-endpoints-when-working-with-node-and-ejs-and-geting-the-det

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!