Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 http post + Nodejs express

I can't get post params on the server. I send post request in Angular 2 app to Nodejs express server. Here my code in Angular 2:

import { Injectable } from 'angular2/core';                                                                                                    
import { Http } from 'angular2/http';

@Injectable()
export class QueryService {
  static get parameters() {                                                                                                                    
    return [[Http]]                                                                                                            
  }                                                                                                                                            
  constructor(http) {                                                                                                            
    this.http = http;                                                                                                                          
  }
  postApi() {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http.post('http://localhost:3001/post_test', JSON.stringify({"id": 1, "name": "2"}), { headers: headers }).toPromise();
  }                                                                                                                                            
}

In the browser I see that post params was send, for example in chrome section "Request Playload" contains my post data. And here my server:

app.js:

var bodyParser = require('body-parser');
app.use(bodyParser.json());                                                                                                                
app.use(bodyParser.urlencoded({extended: true}));                                                                                          

routes/index.js:

exports.post_test = function(req, res) {
    console.log('post_test ', req.body);
}

and the output is "post_test {}"

I can't understand, where is the problem. Because my server works fine, when I used Angular 1 $http service for post queries. Please, help me!

like image 857
user3601435 Avatar asked Oct 19 '22 13:10

user3601435


1 Answers

You forgot to import the Headers class:

import { Injectable } from 'angular2/core';                                                                                                    
import { Http, Headers } from 'angular2/http'; // <----

In this case, the headers aren't sent along with your request but no error is displayed.

like image 143
Thierry Templier Avatar answered Nov 11 '22 11:11

Thierry Templier