node.js - How to make post request from angular to node server -


when print contents of request on node server, can't see user data anywhere.

here node server:

var http = require('http'); http.createserver( function (request, response) {       console.log(request); }).listen(8080); console.log('server running @ http://127.0.0.1:8080/'); 

and here angular2 code:

import { component, oninit } '@angular/core'; import { httpclient } "@angular/common/http"; import { http, response, headers , requestoptions } "@angular/http"; import 'rxjs/add/operator/retry'; // able retry when error occurs import { observable } "rxjs/rx";  @component({   selector: 'app-root',   templateurl: './app.component.html',   styleurls: ['./app.component.css'] })  export class appcomponent implements oninit{   title = 'angular test';   user = { id : 1, name : "hello"};   constructor (private http: http) {}    ngoninit(): void {     let headers = new headers({ 'content-type': 'application/json' });     let options = new requestoptions({ headers: headers });      console.log(this.user);      this.http.post("http://localhost:8080/", this.user, options)     .subscribe(      (err) => {         if(err) console.log(err);         console.log("success");      });   } } 

can me out or explain how handle http request in angular.

that server:

const express = require('express') const bodyparser = require('body-parser'); const app = express()  app.use(bodyparser.json()); app.use(bodyparser.urlencoded({extended: true}) );  app.all("/*", function(req, res, next){   res.header('access-control-allow-origin', '*');   res.header('access-control-allow-methods', 'get,put,post,delete,options');   res.header('access-control-allow-headers', 'content-type, authorization, content-length, x-requested-with');   next(); });  app.post('/ping', function (req, res) {   res.send(req.body) })  app.listen(3000, function () {   console.log('example app listening on port 3000!') }) 

that angular client:

import { component } '@angular/core'; import { httpclient, httpheaders } '@angular/common/http';  @component({   selector: 'app-root',   templateurl: './app.component.html',   styleurls: ['./app.component.css'] }) export class appcomponent {   user = { id : 1, name : 'hello'};    constructor(private http: httpclient) { }    callserver() {     const headers = new httpheaders()           .set('authorization', 'my-auth-token')           .set('content-type', 'application/json');      this.http.post('http://127.0.0.1:3000/ping', json.stringify(this.user), {       headers: headers     })     .subscribe(data => {       console.log(data);     });   } } 

repo https://github.com/kuncevic/angular-httpclient-examples


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -