2 pièce(s) jointe(s)
[Angular 2] Comment faire correctement ma requête POST
Bonjour, je souhaite enregistrer une donnée sur mon serveur REST sous node js,
voici mon serveur rest:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
var express = require("express"),
bodyParser = require("body-parser"),
port = 8000,
app = express();
var MongoClient = require("mongodb").MongoClient;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function(req,res,next){
res.header( 'Access-Control-Allow-Origin' ,'*');
res.header( 'Access-Control-Allow-Methods' ,'GET,PUT,POSTE,DELETE');
res.header( 'Access-Control-Allow-Headers' ,'Content-Type');
next();
});
var router = express.Router();
router.route('/').get(function(req, res){
MongoClient.connect("mongodb://localhost/book", function(error, db) {
if (error) throw error;
db.collection("sommaire").find().toArray(function (error, results) {
if (error) throw error;
console.log(results);
//res.end(results);
res.status(200).json(results);
});
});
})
.post(function(req, res){
console.log(req);
var form_matiere = req.body;
console.log(form_matiere ,"requete post reçu");
MongoClient.connect("mongodb://localhost/book", function(error, db) {
db.collection('sommaire').insert(form_matiere, function(err, records) {
if (err) throw err; });
res.status(200).send();
res.end('insertion de la matiere');
});
})
app.use('/api',router);
app.listen(port, function(){
console.log("ecoute", port);
} ); |
j'ai testé mon serveur avec http request et cela fonctionne lorsque clique sur le bouton POST j'ai la création de donnée certe vide mais elle ont été inscrit
Pièce jointe 232747
ici j'ai fait 3 requêtes, donc 3 id différent, maintenant j'aimerais faire le même test mais avec angular2:
voici ma méthode qui ajoute un élément:
Code:
1 2 3 4 5 6 7 8
|
addMatiere(newMatiere: Sommaire) {
console.log("Ajouter matier",newMatiere);
let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.post(this._urlRest, JSON.stringify(newMatiere), options).catch(this.handleError);; // ...using post request
} |
j'ai vider toutes ls donnée
voici ce que j'ai à la console:
Pièce jointe 232751
je n'arrive pas avoir de tace après "ajouter matière",
coté console du serveur node voici ce que j'ai:
je n'ai pas le résultat de console.log(res)
Code:
1 2 3
|
.post(function(req, res){
console.log(req); |
comment je dois écrire ma requête post ?
merci de vos réponse :)
voici mon mangager sous angular2:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
import {Injectable} from '@angular/core';
import {Sommaire} from './sommaire-data';
import { Http, Response,Headers,RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class SommaireGestionService{
private _matieres = Sommaire.matieres.slice(0);
private _matiereNow:Sommaire; //mémorise matière courant auquel on a sélectionner
private loading:boolean;
private _urlRest :string = 'http://192.168.0.11:8000/api';
constructor(public http: Http) {
}
getAllMatieres():Sommaire[]{
this.loading = true;
this.http.get('http://192.168.0.11:8000/api').subscribe((res: Response) => {
this._matieres = res.json();
this.loading = false;
console.log(res.json());
});
return this._matieres.slice(0);
}
getIdMatiere(id: number): Sommaire {
let matiere = this._matieres.filter(s => s.id == id)[0];
return matiere ? {id: matiere.id, name: matiere.name }: null;
}
addMatiere(newMatiere: Sommaire) {
console.log("Ajouter matier",newMatiere);
let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.post(this._urlRest, JSON.stringify(newMatiere), options); // ...using post request
}
saveMatiere(matiere: Sommaire) {//premet d'éditer un matière
let oldmatiere = this._matieres.filter(s => s.id == matiere.id)[0];
if (oldmatiere) {//si la matière à été trouvé alors il faut la modifier
oldmatiere.name = matiere.name;
}//sinon on ne fait rien
console.log(this._matieres);
}
setMatiereNow(matiere:Sommaire){
this._matiereNow = matiere;
}
getMatierNow(){
return this._matiereNow;
}
kilMat(id: number) {
let oldMat = this._matieres.filter(s => s.id == id)[0];
if (oldMat) {
let matIndex = this._matieres.indexOf(oldMat);
if (matIndex >= 0) {
this._matieres.splice(matIndex, 1);
}
}
}
} |