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);
});
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With