1

When I try to post data from angular to my nodejs backend it doesn't work.

[Backend] This is the function that catches the posted data. I tested it with postman and it worked. The console.log is just for testing. I have also a bodyParser running.

register : function (req, res) {
    console.log(req.body);
    res.json(req.body);
}

[Frontend] This is the function that I call to send the data. I tested it with breakpoints and a console.log and the function is called. I think I tested all the possible ways to format the header.

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';

@Injectable()
export class DataService {
    constructor (private http: Http) {}

    register(user:string): void{
         let headers = new Headers({ 'Content-Type': 'application/json' });
         let options = new RequestOptions({ headers: headers });

         this.http.post('http://127.0.0.1:5000/register', { user }, options);

    }
}

When I put a breakpoint on the this.http.post(...); I get this: link to image

1 Answer 1

2

You need to subscribe to post.

  this.http
       .post('http://127.0.0.1:5000/register', { user }, options)
       .subscribe((result){

             console.log('result',result);

        });

To be more clear , Angualr2 http service is using rxjs Observables , and it's an observable in it's nature and observables are lazy , so unless you subscribe to them , they won't do anything.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes it worked! Thank you! I thought the problem was with the headers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.