How to send data in post body in angular 4
28,709
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);
});
Author by
MANOJ
I go school at DU. I have learned coding through experiments but not through traditional coding classes.
Updated on January 14, 2022Comments
-
MANOJ over 2 years
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); });
-
Vibhor Dube almost 4 yearsFrom Express v4.0, use
app.use(express.json());
in the place of both the lines of bodyParser -var bodyParser = require('body-parser'); router.use(bodyParser.json());