Я изучаю Node.JS с Angular 4. Я создаю образец Node API для простого запроса GET/POST. Моя работа GET работает нормально, и я могу получить данные в Angular. Моя операция OST не вызвана вообще от Angular. Если я использую Postman, я могу вызвать POST успешно, и данные также будут вставлены в базу данных.
Вот мой пример кода для 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]);
});
Это отлично работает с Postman, и я получаю 201.
Вот мой код Angular 4:
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');
}
}
Что здесь не так?