MANOJ
MANOJ

Reputation: 736

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);
});

Upvotes: 7

Views: 34807

Answers (2)

rajquest
rajquest

Reputation: 711

if the body payload contains application/x-www-form-urlencoded values then post methods expects string value like below const body = 'client_id=ApiClient&grant_type=password&scope=UiApi&username=' + username +'&password=' +password;

getLoginCredentialsAccessToken(username: string, password: string) 
: Observable<AccessToken>{

const headersList = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' });

const body = 'client_id=ApiClient&grant_type=password&scope=UiApi&username=' + username +'&password=' +password;
     
return this.http.post<AccessToken>(this.tokenEndpoint, body, { headers: headersList});
  }

Upvotes: 0

MANOJ
MANOJ

Reputation: 736

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);
});

Upvotes: 8

Related Questions