0

The GET method works fine but when i call the POST method on my angular project it seems like the POST function on nodeJs doesn't get called. What am i doing wrong ?

Angular Service:

getAllProducts():  Observable<Product[]> {
return this.http.get<Product[]>('http://localhost:3000/api/content');
}

insertProduct(product: Product): Observable<Product> {
return this.http.post<Product>('http://localhost:3000/api/content', product);
}

server.js:

app.get('/api/content', function (req, res, next) {
    // query to the database and get the records
    mc.query('select * from testContent', function (err, recordset) {

        if (err) console.log(err)

        // send records as a response
        res.send(recordset); 
    });
});


app.post("/api/content",function(req , res, next){

    console.log('I will not get printed');

    mc.query('INSERT INTO testContent (productName,productCode) VALUES (\''+req.body.productName + '\',\'' + req.body.productCode + '\')',function (err, recordset) {

        if (err) console.log(err)

        // send records as a response
        res.send(recordset);

    });

});
  • Refer this post: [How do I consume the JSON POST data in an Express application](https://stackoverflow.com/questions/10005939/how-do-i-consume-the-json-post-data-in-an-express-application) for some guidance. – aaruja Dec 24 '18 at 14:46

1 Answers1

1

Maybe you need a "Content-Type" header in your post request like :

import { HttpClient, HttpHeaders } from '@angular/common/http';

insertProduct(product: Product): Observable<Product> {
  return this.http.post<Product>('http://localhost:3000/api/content', product, {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  });
}
Johan Rin
  • 1,660
  • 2
  • 16
  • 38