I'm learning 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 OST operation isn't getting called at all from Angular. If I use Postman, I'm able to call POST successfully and data also gets 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 get 201.
Here is my Angular 4 code:
import { Injectable } from '@angular/core';
import { Http, Response,RequestOptions, Request, RequestMethod, Headers} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import { Group } from './group';
@Injectable()
export class GroupsService{
private _GroupsUrl = 'http://localhost:5000/api/groups';
constructor(private _http: Http){};
getGroups(): Observable<Group[]> {
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Accept', 'application/json');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
headers.append('Access-Control-Allow-Origin', '*');
//headers.append('Access-Control-Allow-Headers', "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding");
let options = new RequestOptions({ method: RequestMethod.Post, headers: headers, url:this._GroupsUrl });
//debugger;
return this._http.get(this._GroupsUrl)
.map((Response: Response) => <Group[]>Response.json()[0])
//.do(data => console.log ('ALL: ' + JSON.stringify(data)))
.catch(this.handleError);
}
CreateGroup(GroupM): Observable<string>{
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT, OPTIONS');
headers.append('Access-Control-Allow-Origin', 'http://localhost:4200');
headers.append('Access-Control-Allow-Headers', "X-Requested-With, Content-Type");
//let options = new RequestOptions({ method: RequestMethod.Post, headers: headers, body:JSON.stringify(GroupM), url:this._GroupsUrl });
let options = new RequestOptions({ method: RequestMethod.Post});
console.log('Calling ' + this._GroupsUrl + ' with body as :' + JSON.stringify(GroupM) + ' and request options are : ' + JSON.stringify(options));
var req = new Request(options.merge({
url: this._GroupsUrl
}));
debugger;
//return this._http.post(this._GroupsUrl,GroupM)
return this._http.post(req.url,JSON.stringify(GroupM),options)
.map(res => res.json())
.do(data => console.log ('ALL: ' + JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(error:Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server Error');
}
}
What is wrong here?
Don't stringify the POST data in HTTP POST. Simply pass the object.
Finally able to resolve it using promise and it resolves the issue. Not sure what exactly is the issue with observable.
> CreateGroup(GroupObj:Group) : Promise<Group>{
return this._http
.post(this._GroupsUrl,JSON.stringify(GroupObj),{headers: this.headers})
.toPromise()
.then(res => res.json().data as Group)
.catch(this.handleError);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With