How to make post request from angular to node server

22,352

Solution 1

That is your 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 is your angular client:

import { Component } from '@angular/core';
import { HttpClient, HttpHeaders } from '@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

Solution 2

I've written this inside our documentation page but since it is deprecated now I'll copy it here.

Your node part, app.js, should look like (assuming you are using expressjs along with node.js):

app.js:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var bodyParser = require('body-parser');

server.listen(process.env.PORT || 8080, function(){
    console.log("Server connected. Listening on port: " + (process.env.PORT || 8080));
});

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

app.use( express.static(__dirname + '/front' ) );

app.post('/test', function(req,res){ //**** http request receiver ****
  var myTestVar = "Hello World";
  return res.send(myTestVar);
});

//send the index.html on every page refresh and let angular handle the routing
app.get('/*',  function(req, res, next) {
    console.log("Reloading");
    res.sendFile('index.html', { root: __dirname }); 
});

With this node configs when you post something to localhost:8080/test, you will receive myTestVar as a response in your subscribe callback.

Share:
22,352
spuemaacne
Author by

spuemaacne

Updated on August 27, 2020

Comments

  • spuemaacne
    spuemaacne over 3 years

    When I print contents of request on Node server, I can't see the user data anywhere.

    Here is my Node server:

    var http = require('http');
    http.createServer( function (request, response) {  
        console.log(request);
    }).listen(8080);
    console.log('Server running at http://127.0.0.1:8080/');
    

    And here is Angular2 code:

    import { Component, OnInit } from '@angular/core';
    import { HttpClient } from "@angular/common/http";
    import { Http, Response, Headers , RequestOptions } from "@angular/http";
    import 'rxjs/add/operator/retry'; // to be able to retry when error occurs
    import { Observable } from "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 anyone help me out or explain how to handle http request in angular.