aldy aldy - 7 months ago 104
SQL Question

How to make login API in node.js using mysql database

i am new in node.js and i want to make a login api using express and mysql database,Please share with me your idea and example.

Answer

Firstly you should familiarise yourself with the express framework.

Secondly you'll want to create a mysql database with the following tables:

  1. Users
    • userId | name | other fields...
  2. Authentication_tokens
    • userId | token

These will be the building blocks for your application. Basically from here you'll be able to authenticate http requests with a single token, this token will be assigned to a userId.

Once we have the database setup we can start to add in the express routes.

  1. Add in an authentication route

The below route will mean that all requests that have the /api/v1/ prefix in front of them will go through the ./api/middlewares/validateRequest file before continuing.

app.all('/api/v1/*', [require('./app/middlewares/validateRequest')]); // Authenticate all api/v1/ req

The validateRequest file could look something like this:

module.exports = function(req, res, next) {
  // When performing a cross domain request, you will recieve
  // a preflighted request first. This is to check if our the app
  // is safe. 
  // We skip the token outh for [OPTIONS] requests.
  //if(req.method == 'OPTIONS') next();

    // CHECK FOR A token inside the header of the request
    var token = (req.body && req.body.access_token) || (req.query && req.query.access_token) || req.headers['x-access-token'];
    var key = (req.body && req.body.x_key) || (req.query && req.query.x_key) || req.headers['x-key'];
    ... DO ALL YOUR MYSQL QUERIES HERE TO VALIDATE THE TOKEN
  1. Add in your other routes below...

If you want a route to be authenticated, then add in the api/v1/ prefix.

app.use('/api/v1/post/', require('./app/services/post/index.js')); 

This is a very basic example. I suggest you look at some tutorials! E.g

  1. https://codeforgeek.com/2015/01/nodejs-mysql-tutorial/
  2. http://teknosains.com/i/simple-crud-nodejs-mysql

If you don't want to build the mysql database and queries yourself, you could look into using an ORM such as sequelize: https://github.com/sequelize/sequelize