empleados-crear.component.ts
import { Component, OnInit } from '@angular/core';
import { Empleado } from '../modelo-de-datos/empleados';
import { NgForm } from '@angular/forms';
import { EmpleadoServiceService } from '../servicios/empleado-service.service';
@Component({
selector: 'app-empleados-crear',
templateUrl: './empleados-crear.component.html',
styleUrls: ['./empleados-crear.component.css'],
providers:[EmpleadoServiceService]
})
export class EmpleadosCrearComponent implements OnInit {
public a:number;
public empleado_nuevo:Empleado;
public fecha_nacimiento:Date;
constructor(
private empleadoService:EmpleadoServiceService
) {
}
ngOnInit() {
this.fecha_nacimiento = new Date();
this.empleado_nuevo = new Empleado('','','','',0,this.fecha_nacimiento);
}
limpiarFormulario(form?:NgForm){
this.empleado_nuevo = new Empleado('','','','',0,this.fecha_nacimiento);
}
insertarEmpleado(){
console.log(this.empleado_nuevo);
//console.log(form.value)
this.empleadoService.addEmpleado(this.empleado_nuevo).subscribe(
res=>{
console.log(res);
},
error=>{
console.log(error);
}
);
}
}
empleado-service.service.ts
import { Injectable } from '@angular/core';
import { Empleado } from '../modelo-de-datos/empleados';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class EmpleadoServiceService {
private empleado: Empleado;
private empleados: Empleado[];
//readonly url_api = 'localhost:3000/getEmpleados';
constructor(
private http: HttpClient
) { }
getEmpleados() {
return this.http.get('localhost:3000/getEmpleados').subscribe(
res=>{
console.log(res);
},
error=>{
console.log(error);
}
);
}
addEmpleado(empleado_nuevo: Empleado){
return this.http.post('localhost:3000/addEmpleado',empleado_nuevo);
}
}
Consola Chrome
Empleado {dni: "66666666Z", nombre: "Luis", apellidos: "Rodriguez Guzman", departamento: "Prestamatica", sueldo: 12300, …}
apellidos: "Rodriguez Guzman"
departamento: "Prestamatica"
dni: "66666666Z"
fecha_nacimiento: "2018-11-08"
nombre: "Luis"
sueldo: 12300
__proto__: Object
zone.js:2969 Access to XMLHttpRequest at 'localhost:3000/addEmpleado' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
empleados-crear.component.ts:46
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for (unknown url): 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: null
__proto__: HttpResponseBase
Consola Firefox
error: error { target: XMLHttpRequest, isTrusted: true, lengthComputable: false, … }
headers: Object { normalizedNames: Map(0), lazyUpdate: null, headers: Map(0) }
message: "Http failure response for (unknown url): 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: null
<prototype>: Object { constructor: HttpErrorResponse()
}
index.js de mi servidor en nodejs
const express = require('express');
const app = express();
const cors = require('cors');
const morgan = require('morgan');
const {mongoose} = require('./database');
//settings
app.set('port',3000);
//middleware
app.use(morgan('dev'));
app.use(express.json());
app.use(cors({
origin:'http://localhost:4200'
}));
//CORS -2
/*
const corsOptions = {
origin: [process.env.URL, 'http://localhost:4200']
}
*/
app.use(cors(corsOptions))
app.options('*', cors(corsOptions))
//FIN CORS 2
//routes
app.use(require('./routes/empleado.routes'));
//starting server
app.listen(3000,()=>{
console.log('Servidor en el puerto '+app.get('port'));
});
this.http.get('localhost
sino no sabe que protocolo comparar (http/https/data)