Saturday, 22 April 2017

Unable to make app.post working using nodeJs

I am trying to connect my Angular2 to my nodeJs server. I have an authentification form which makes a post request. And I would like to use node to handle the post request. But so far I am unable to make my post request working. What I am missing?

This is my server.js which points to the folder dist in which i made the build of angular.

const express = require('express');
const path = require('path');
const http = require('http');

var walker = require('node-sync-walker');

const bodyParser = require('body-parser');


// Get our API routes
const api = require('./server/routes/api');

var app = express();

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

// Set our api routes
app.use('/api', api);

// Catch all other routes and return the index file
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

walker.routeWalker(__dirname + '/server/routes', app);

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));

This is my api.js

var users = [{username: "user", password: "password"}];

var router = require('express').Router();

module.exports = function(app) {
  router.post('/api/authenticate',
    function(req, res) {

      console.log("print something");

      let params = JSON.parse(req.body);

      // find if any user matches login credentials
      let filteredUsers = users.filter(user => {
          return user.username === params.username && user.password === params.password;
    });

      if (filteredUsers.length) {

        res.sendStatus(200);

      } else {
        console.log("print something else");

        return res.sendStatus(400)
      }

      //return;
    });
}



via edkeveked

No comments:

Post a Comment