Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send data in post body in angular 4

Below is the code to make post request:

export class AuthenticationService {

    private authUrl = 'http://localhost:5555/api/auth';

    constructor(private http: HttpClient) {}

    login(username: string, password: string) {
      console.log(username);
      let data = {'username': username, 'password': password};
      const headers = new HttpHeaders ({'Content-Type': 'application/json'});
      //let options = new RequestOptions({headers: headers});
      return this.http.post<any>(this.authUrl, JSON.stringify({data: data}), {headers: headers});
    }
}

Below is the node code where I am trying to access the request body, Request body is null in the helow case:

router.use(express.static(path.join('webpage')));

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

router.use(bodyParser.urlencoded({ extended: true }));

router.post('/api/auth', function(req, res){
  console.log(req.body);
  console.log(req.body.username + ":" + req.body.password);
});
like image 610
MANOJ Avatar asked Apr 16 '18 07:04

MANOJ


1 Answers

Request was sent successfully using below method:

Angular:

login(username: string, password: string) {
      const data = {'username': username, 'password': password};
      const config = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
      return this.http.post<any>(this.authUrl, data, config)
                                .map(res => {
                                  console.log(res);
                                  if (res.user === true) {
                                    localStorage.setItem('currentUser', res.user);
                                    localStorage.setItem('role', res.role);
                                  }
                                  return res;
                                  },
                                  err => {
                                    return err;
                                  }
                                );

    }

Node

var bodyParser = require('body-parser');
router.use(bodyParser.json());

router.post('/api/auth', function(req, res){
  console.log("request received " + req.body);
});
like image 147
MANOJ Avatar answered Oct 21 '22 08:10

MANOJ