Ejemplo 1 (Con formulario):
Cliente:
app.component.html
<form (ngSubmit)="onSubmit()" method="POST">
Usuario: <input type="text" [(ngModel)]="name" name="name">
<br>
Password:<input type="text" [(ngModel)]="password" name="password">
<br>
<input type="submit" value="Enviar" />
</form>
app.component.ts
import { Component } from '@angular/core';
import { DataService } from './data.service';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private data : DataService) {}
title = 'app';
name: string;
password: string;
onSubmit() {
console.log(this.name + " " + this.password);
this.data.login(this.name, this.password).subscribe((datos) => {
console.log(datos);
});
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { DataService } from './data.service';
import { HttpModule } from '@angular/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [DataService],
bootstrap: [AppComponent]
})
export class AppModule { }
data.service.ts
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class DataService {
constructor(public http: Http) { }
login(name: string, password: string) {
console.log("llamando al servicio");
return this.http.post("http://localhost:3000/login", {name: name, password: password})
.map(res => res.json());
}
}
Servidor
var express=require('express');
var app=express();
var bodyParser = require('body-parser');
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
var router=express.Router();
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended: false}));
router.get('/', function(req, res) {
res.send("Hello World!");
});
router.post('/login',testFunction);
router.get('/prueba', function(req, res) {
console.log("prueba...");
res.send(JSON.stringify("ok"));
});
function testFunction(req,res) {
var name=req.body.name;
var password=req.body.password;
console.log("Name:" + name + " Password:" + password);
res.send(JSON.stringify("ok"));
}
app.use(router);
//module.exports=router;
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
Ejemplo 2:
router.post('/competidores/guardar', function (req, res) {
var nombre = req.body.nombre;
var direccion = req.body.direccion;
console.log(nombre);
res.send(nombre);
});
Para testearlo con Postman:
Elegir POST
Luego Body
x-www-form-urlencoded
Ejemplo con insert:
router.post('/competidores/guardar', function (req, res) {
var body = req.body;
var resultado = '';
con.query(
'INSERT INTO competidor (numero, nombres, apellidos, cedula, apodo, barrio, nacionalidad, direccion, telefono, ' +
'celular, email, estatura, experiencia, fecha_nacimiento, gimnasio, entrenador, sociedad, peso) ' +
'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[body.numero, body.nombres, body.apellidos, body.cedula, body.apodo, body.barrio, body.nacionalidad,
body.direccion, body.telefono, body.celular, body.email, body.estatura, body.experiencia,
body.fecha_nacimiento, body.gimnasio, body.entrenador, body.sociedad, body.peso],
function (err, results) {
if (err == null)
resultado = "OK";
else
resultado = err;
console.log(resultado);
}
);
res.send(resultado);
});

No hay comentarios:
Publicar un comentario