Sunday, 7 May 2017

Node JS API isn't get called

I'm learing node.js with angular 4. I build a sample node api for simple get/post request. My get operation works fine and i am able to fetch data in angular. My post operation isn't getting called at all from angular. If i use POSTMAN, i'm able to call post successfully and data also get inserted in database.

Here is my sample code for node post

app.post('/groups', function (req, res, next){


res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
res.header("Access-Control-Allow-Methods", "GET, POST","PUT");

console.log('Request received with body' + req.body);
//DEV AWS MySQL
var mysql = require('mysql');

var connection = mysql.createConnection({
                      host     : 'xxxxxxx',
                      user     : 'xxxxxxx',
                      password : 'xxxxxxx',
                      database : 'xxxxxxx',
                      port     : 3306
});
connection.connect();

connection.query('CALL storedprocedure(?, ?, ?, ?, ?, ?)', [req.body.group_avatar_image,req.body.name,req.body.display_name,req.body.unique_id,req.body.description,req.body.adzone], function (err, results, fields){

    if (err)
        res.send(results);

    //res.status(201).send("Groups created successfully");
    res.status(201).send(results[0]);
});

This works fine with POSTMAN and i can get 201...

Here is my angular 4 code

    CreateGroup(Group): Observable<Group>{

    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
    //let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });    

    console.log('Calling ' + this._GroupsUrl + ' with Options :' + options.headers.toJSON());
    return this._http.post(this._GroupsUrl,Group,options)
                .map((Response: Response) => <string>Response.json()[0])
                .do(data => console.log('Service response: ' + data))
                .catch(this.handleError);
}

What is wrong here?



via jatin

No comments:

Post a Comment