当我尝试在angular2中提交表单时出错

时间:2017-03-22 03:38:33

标签: angular typescript

我收到以下错误

Error Screenshot

Lo siento si estoy preguntando algo que pueda estar ya en el foro,pero me encuentro desarrollando una app la cual genera distintos PDF'stravésde3 tipos de formularios y al momento de hacer submit me encuentro con este error el cual no he podido solucionar。

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { InformeService } from './informe.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
declare var jQuery: any;
declare var $: any;

@Component({
  selector: 'app-informe',
  templateUrl: './informe.component.html',
  styleUrls: ['./informe.component.css'],
  providers: [InformeService]
})
export class InformeComponent implements OnInit {

  objGeneralIndex: number = 1;
  objGeneral = [{ id: 1, text: "" }];
  objEspecificos = [{ id: 1, text: "" }];
  objEspecificosIndex: number = 1;

  formInforme: FormGroup;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private service: InformeService,
    private fb: FormBuilder
  ) { this.crearControles(); }

  ngOnInit() {
    $("#infoBasic").show(500);
    $("#objGeneral").hide(500);
    $("#objEspec").hide(500);
  }
  crearControles() {
    this.formInforme = this.fb.group({
      tituloInforme: '',
      fechaInforme: '',
      objGeneral: '',
      objEspec: ''
    })
  }
  guardarInforme() {
    this.service.addInforme(this.formInforme.value)
      .subscribe(
      rt => console.log(rt),
      er => console.log(er),
      () => console.log('Terminado')
      );
  }

  addObjetivo(): void {
    this.objGeneralIndex++;
    this.objGeneral.push({ id: this.objGeneralIndex, text: "" });
  }
  delObjGral(obj): void {
    for (var i = 0; i < this.objGeneral.length; i++) {
      if (this.objGeneral[i].id == obj.id) {
        this.objGeneral.splice(i, 1);
      }
    }
  }

  addObjectivoEspecifico(): void {
    this.objEspecificosIndex++;
    this.objEspecificos.push({ id: this.objEspecificosIndex, text: "" });
  }

  delObjEspecifico(obj): void {
    for (var i = 0; i < this.objEspecificos.length; i++) {
      if (this.objEspecificos[i].id == obj.id) {
        this.objEspecificos.splice(i, 1);
      }
    }
  }
  showInfoBasic() {
    $("#infoBasic").show(500);
    $("#objGeneral").hide(500);
    $("#objEspec").hide(500);
  }
  showObjGral() {
    $("#infoBasic").hide(500);
    $("#objGeneral").show(500);
    $("#objEspec").hide(500);
  }
  showObjEspec() {
    $("#infoBasic").hide(500);
    $("#objGeneral").hide(500);
    $("#objEspec").show(500);
  }
}
/* DivTable.com */
.divTable{
	display: table;
	width: 100%;
}
.divTableRow {
	display: table-row;
}
.divTableHeading {
	background-color: #EEE;
	display: table-header-group;
}
.divTableCell, .divTableHead {
	text-align: center;
	border: 1px solid #999999;
	display: table-cell;
	padding: 3px 10px;
}
.divTableHeading {
	background-color: #EEE;
	display: table-header-group;
	font-weight: bold;
}
.divTableFoot {
	background-color: #EEE;
	display: table-footer-group;
	font-weight: bold;
}
.divTableBody {
	display: table-row-group;
}

button#addObjetivo, #addObjetivoEspec{
    float: right;
    margin-top:-60px;
}
button#btn_sent {
    float: right;
    margin-top: -81px;
    margin-right: 12%;
}
#control-buttons{
    float: right;
    margin-top:-50px;
}
#dellCell{
    width:5%;
}
#bodyInforme {
	width: 90%;
	margin-left: auto;
	margin-right: auto;
}
#panelInforme {
	height: 480px;
}
#overflowGral, #overflowEspec{
	height: 300px;
	overflow: auto;
}
<div class="container">
  <div id="panelInforme" class="panel panel-default">
    <div id="bodyInforme" class="panel-body">
      <h3>Formulario Creación - Informe de Gestion</h3>
      <div id="control-buttons">
        <button (click)="showInfoBasic()" id="btn_general" type="button" class="btn btn-info">1</button>
        <button (click)="showObjGral()" id="btn_especifico" type="button" class="btn btn-info">2</button>
        <button (click)="showObjEspec()" id="btn_especifico" type="button" class="btn btn-info">3</button>
      </div><hr>
      <form novalidate [formGroup]="formInforme">
        <button id="btn_sent" (click)="guardarInforme()" type="submit" class="btn btn-success">Enviar Informe</button>
        <div id="infoBasic">
          <h4>Información Básica</h4>
          <hr>
          <div class="form-group">
            <label for="tituloInforme">Titulo de Informe</label>
            <input id="tituloInforme" formControlName="tituloInforme" type="text" class="form-control" placeholder="Titulo de Informe">
          </div>
          <div class="form-group">
            <label for="fechaInforme">Fecha:</label>
            <input id="fechaInforme" formControlName="fechaInforme" type="text" class="form-control">
          </div>
        </div>
        <div id="objGeneral">
          <div id="objGral" class="form-group">
            <h4>Ingrese Objetivos Generales</h4>
            <hr>
            <button (click)="addObjetivo()" id="addObjetivo" type="button" class="btn btn-success">Agregar Fila</button>
            <div id="overflowGral">
              <div class="divTable">
                <div class="divTableBody">
                  <div class="divTableRow">
                    <div class="divTableCell">#</div>
                    <div class="divTableCell">Puntos</div>
                  </div>
                  <div *ngFor="let obj of objGeneral; let i = index;" id="tbl_objGeneral" class="divTableRow">
                    <div class="divTableCell">{{ (i+1) }}</div>
                    <div class="divTableCell">
                      <input id="objGeneral" formControlName="objGeneral" class="form-control" value="{{ obj.text }}" type="text" placeholder="Objetivo General">
                    </div>
                    <div class="divTableCell" id="dellCell">
                      <button (click)="delObjGral(obj)" type="button" class="btn btn-danger">Eliminar</button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div id="objEspec" class="form-group">
          <h4>Ingrese Objetivos Específicos</h4>
          <hr>
          <button (click)="addObjectivoEspecifico()" id="addObjetivoEspec" type="button" class="btn btn-success">Agregar Fila</button>
          <div id="tbl_espec" class="divTable">
            <div id="overflowGral">
              <div class="divTableBody">
                <div class="divTableRow">
                  <div class="divTableCell">#</div>
                  <div class="divTableCell">Puntos</div>
                </div>
                <div *ngFor="let obj of objEspecificos; let i = index;" id="tbl_objGeneral" class="divTableRow">
                  <div class="divTableCell">{{ (i+1) }}</div>
                  <div class="divTableCell">
                    <input id="objEspec" formControlName="objEspec" class="form-control" value="{{ obj.text }}" type="text" placeholder="Ingrese Objetivos Específicos">
                  </div>
                  <div class="divTableCell" id="dellCell">
                    <button (click)="delObjEspecifico(obj)" type="button" class="btn btn-danger">Eliminar</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="container">
  <div id="panelInforme" class="panel panel-default">
    <div id="bodyInforme" class="panel-body">
      <h3>Formulario Creación - Informe de Gestion</h3>
      <div id="control-buttons">
        <button (click)="showInfoBasic()" id="btn_general" type="button" class="btn btn-info">1</button>
        <button (click)="showObjGral()" id="btn_especifico" type="button" class="btn btn-info">2</button>
        <button (click)="showObjEspec()" id="btn_especifico" type="button" class="btn btn-info">3</button>
      </div>
      <hr>
      <form novalidate [formGroup]="formInforme">
        <button id="btn_sent" (click)="guardarInforme()" type="submit" class="btn btn-success">Enviar Informe</button>
        <div id="infoBasic">
          <h4>Información Básica</h4>
          <hr>
          <div class="form-group">
            <label for="tituloInforme">Titulo de Informe</label>
            <input id="tituloInforme" formControlName="tituloInforme" type="text" class="form-control" placeholder="Titulo de Informe">
          </div>
          <div class="form-group">
            <label for="fechaInforme">Fecha:</label>
            <input id="fechaInforme" formControlName="fechaInforme" type="text" class="form-control">
          </div>
        </div>
        <div id="objGeneral">
          <div id="objGral" class="form-group">
            <h4>Ingrese Objetivos Generales</h4>
            <hr>
            <button (click)="addObjetivo()" id="addObjetivo" type="button" class="btn btn-success">Agregar Fila</button>
            <div id="overflowGral">
              <div class="divTable">
                <div class="divTableBody">
                  <div class="divTableRow">
                    <div class="divTableCell">#</div>
                    <div class="divTableCell">Puntos</div>
                  </div>
                  <div *ngFor="let obj of objGeneral; let i = index;" id="tbl_objGeneral" class="divTableRow">
                    <div class="divTableCell">{{ (i+1) }}</div>
                    <div class="divTableCell">
                      <input id="objGeneral" formControlName="objGeneral" class="form-control" value="{{ obj.text }}" type="text" placeholder="Objetivo General">
                    </div>
                    <div class="divTableCell" id="dellCell">
                      <button (click)="delObjGral(obj)" type="button" class="btn btn-danger">Eliminar</button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div id="objEspec" class="form-group">
          <h4>Ingrese Objetivos Específicos</h4>
          <hr>
          <button (click)="addObjectivoEspecifico()" id="addObjetivoEspec" type="button" class="btn btn-success">Agregar Fila</button>
          <div id="tbl_espec" class="divTable">
            <div id="overflowGral">
              <div class="divTableBody">
                <div class="divTableRow">
                  <div class="divTableCell">#</div>
                  <div class="divTableCell">Puntos</div>
                </div>
                <div *ngFor="let obj of objEspecificos; let i = index;" id="tbl_objGeneral" class="divTableRow">
                  <div class="divTableCell">{{ (i+1) }}</div>
                  <div class="divTableCell">
                    <input id="objEspec" formControlName="objEspec" class="form-control" value="{{ obj.text }}" type="text" placeholder="Ingrese Objetivos Específicos">
                  </div>
                  <div class="divTableCell" id="dellCell">
                    <button (click)="delObjEspecifico(obj)" type="button" class="btn btn-danger">Eliminar</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

2 个答案:

答案 0 :(得分:2)

解决问题的关键在于错误行 - Response to preflight request doesn't pass access control check。这意味着服务器由于CORS而不允许请求通过。您必须在服务器头文件中定义访问控制源,如下所示 -

app.use(function(req, res, next) {
 res.header('Access-Control-Allow-Origin', '*')
 res.header( "Access-Control-Allow-Methods" , "GET,POST,PUT,DELETE,OPTIONS")
 res.header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, x-access-token, x-email-id")
 res.header("Access-Control-Expose-Headers", ")
if (req.method === 'OPTIONS') return res.send(200)
next()
})

res.header('Access-Control-Allow-Origin', '*')是你服务器中应该有的东西。

答案 1 :(得分:0)

在chrome上运行代码时会发生此类错误。

您可以下载chrome的cors插件并在页面上启用它。

之前发生在我身上,这解决了它。