Monday 1 May 2017

http post from angular 2 client to nodejs req,param(param) returning undefined

I tried posting data from angular 2 client to nodejs server. I sending the data in json format but my node server is returning undefined while accessing the key value pair in nodejs routes via req.param function. I have attached my code files below, please help me in solving this


server.ts code

import {Injectable} from '@angular/core';
import {Http, Response, Headers, RequestOptions} from "@angular/http";
import {Observable} from 'rxjs/Rx';


@Injectable()
export class HttpServices{
    constructor(private http:Http){}


    login(credentials:Object){
        let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
        let options = new RequestOptions({headers: headers});

        console.log("into http"+credentials);
        let body = JSON.stringify(credentials);
        console.log("into server"+body);
        return this.http.post('http://localhost:3000/authentication/login', body, headers).map((res:Response) => res.json());
    }
}


app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');
var common = require('./routes/common');
var labserver = require('./routes/labserver');
var authentication = require('./routes/authentication');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

app.use('/labserver',labserver);
app.use('/authentication',authentication);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;


authentication.js

var express = require('express');
var router = express.Router();
var common = require('./common.js');
var autoIncrement = require('mongoose-auto-increment');
var cors = require('cors');

autoIncrement.initialize(common.conn);

var RegisterSchema = common.Schema({

    employName: String,
    emailID: String,
    userID: String,
    passWord: String,
    designation: String,
    contactNo: String
});

RegisterSchema.plugin(autoIncrement.plugin, {
    model: 'Users',
    field: 'userCount',
    startAt: 00,
    incrementBy: 1
});


var UserTable = common.conn.model('Users',RegisterSchema);

router.post('/register',function(req,res,next){

    var password = req.param('password');
    var emailvalue = req.param('email');

    UserTable.findOne({$and:[{emailID:emailvalue}]}).exec(function(err, result){
        if(err)
            console.log(err);
        else if(result == null){

            var user = new UserTable({

                    employName: req.param('name'),
                    emailID: req.param('email'),
                    userID: emailvalue.substring(0,emailvalue.indexOf('@')),
                    passWord: req.param('password'),
                    designation: req.param('designation'),
                    contactNo: req.param('contactno')
                });

                user.save(function(err){
                    if(err)
                        console.log(err);
                    console.log('Registered successfully');
                });
                res.send('User registered successfully');
        }

        else 

            res.send('User already exist');


    });



});

router.post('/login', cors(), function(req,res,next){
    var userid = req.param('userid');
    var password = req.param('password');

    console.log("UserID: "+userid+" password: "+password);

    UserTable.findOne({$and:[{userID:userid},{passWord:password}]}).exec(function(err, authentication){
        if(err)
            res.send(err);
        else if(authentication == null){
            res.send('User not fount');
            console.log('User not fount');
        }

        else {
            res.send('Authentication successful');
            console.log('Authentication successful');
        }



    });

});

module.exports = router;



via Vignesh Viki

No comments:

Post a Comment