简体   繁体   English

错误500后球衣

[英]Error 500 post angular jersey

I have a problem in jersey restfull. 我在球衣充实方面有问题。 When I execute my update operation, the console of eclipse and console of browser show an error. 当我执行更新操作时,eclipse的控制台和浏览器的控制台显示错误。

for console of eclipse, the error is: 对于eclipse的控制台,错误是:

    GRAVE: Servlet.service() for servlet [JerseyWebApplication] in context with path [/APIRest] threw exception [java.lang.IllegalArgumentException: argument type mismatch] with root cause
java.lang.IllegalArgumentException: argument type mismatch
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.yasson.internal.model.SetWithSetter.internalSetValue(SetWithSetter.java:27)

for console of browser, the error is: 对于浏览器的控制台,错误是:

POST http://localhost:8081/APIRest/resources/langue/update 500 (Erreur Interne de Servlet)
localhost/:1 Failed to load http://localhost:8081/APIRest/resources/langue/update: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 500.
update-langue.component.ts:31 Error saving langue!
(anonymous) @ update-langue.component.ts:31

It's my DAO code 这是我的DAO代码

@Override
    public void update(Langue object) {
        // TODO Auto-generated method stub
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.merge(object);
            em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("Erreur lors de la mise a jour d'une Langue");
        } finally {
            if (em.getTransaction().isActive())
                em.getTransaction().rollback();
            em.close();
        }

    }

It's my rest code 这是我的其余代码

@Path("/update")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public void update(Langue langue) {
        langueDao.update(langue);
    }

It's my angular code service 这是我的角度代码服务

    import {Injectable} from '@angular/core';
    import {Http, Response, RequestOptions, Headers, ResponseContentType} from '@angular/http';
    import {AppSettingsService} from "./config.service";
    import { Langue } from "./langue";
    import {Observable} from 'rxjs/Observable';

    @Injectable()
    export class LangueService {

      private baseUrl: string = '';
      private settings: any;

      constructor(private http: Http, private appSettingsService: AppSettingsService) {
        this.appSettingsService.getSettings()
          .subscribe(settings => {
            this.settings = settings;
            this.baseUrl = this.settings.pathAPI + "/langue";
          });

      }
      // lister toutes les Langues
      getAll(): Observable<any[]> {
        let langue$ = this.http
          .get(`http://localhost:8081/APIRest/resources/langue/getall`, this.appSettingsService.setHeaders())
          .map((response: Response) => response.json())
        return langue$;
      }
//create langue
      create(langue: Langue): Observable<Response> {
        return this.http.post(`http://localhost:8081/APIRest/resources/langue/add`, JSON.stringify(langue), this.appSettingsService.setHeaders());
      }
      //delete a langue
      delete(langue: any): Observable<Response> {
        return this.http.post(`http://localhost:8081/APIRest/resources/langue/delete`, JSON.stringify(langue), this.appSettingsService.setHeaders());
      }
      // modifier une langue
      update(langue:Langue) {
        return this.http.post('http://localhost:8081/APIRest/resources/langue/update', JSON.stringify(langue), this.appSettingsService.setHeaders());
      }
    }

It's my update-langue.component.ts 这是我的update-langue.component.ts

import { Langue } from "../langue";
import { LangueService } from "../langue.service";
import { LangueComponent } from "../langue/langue.component";
import { Component, OnInit, Input } from '@angular/core';
import { Observable } from "rxjs";

@Component({
  selector: 'app-update-langue',
  templateUrl: './update-langue.component.html',
  styleUrls: ['./update-langue.component.css']
})
export class UpdateLangueComponent implements OnInit {
  @Input() langue: Langue = new Langue; 


  constructor(private langueService: LangueService, private langueComponent: LangueComponent) { }

  ngOnInit() {
    this.langueService.getAll();
  }

  updateLangue() {
    this.langueService.update(this.langue).subscribe(
      data => {
                // refresh the list
                this.langueComponent.getAll()
                alert('Modification avec succes');
                return true;
              },
      error => {
                console.error("Error saving langue!");
                return Observable.throw(error);
               }
    );
  }

}

It's my langue.component.ts 这是我的langue.component.ts

import { Langue } from "../langue";
import { LangueService } from '../langue.service';
import { Component, OnInit } from '@angular/core';
import { Observable } from "rxjs";

@Component({
  selector: 'app-langue',
  templateUrl: './langue.component.html',
  styleUrls: ['./langue.component.css']
})
export class LangueComponent implements OnInit {
  public langues;
  langue: Langue;
  constructor(private langueService: LangueService) { }

  ngOnInit() {
    this.getAll();
  }

  selectedLangue: Langue;
  modifedLangue: Langue
  getAll() {
    this.langueService.getAll().subscribe(
      data => { this.langues = data }, err => console.error(err), () => console.log('done loading langues'));
  }

  detail(langue: Langue){
    this.selectedLangue = langue;
  }

  modification(langue: Langue){
    this.modifedLangue = langue;
  }

  delete(langue) {

    if (confirm("Are you sure you want to delete " + this.langue.Id + "" + this.langue.cod + "?")) {
        this.langueService.delete(this.langue).subscribe(
          data => {
             // refresh the list
             this.getAll();
             return true;
          },
          error => {
           console.error("Error deleting langue!");
           return Observable.throw(error);
         }
      );
    }
  }
}

It's my lang.component.html 这是我的lang.component.html

<app-new-langue></app-new-langue>
<kendo-grid [data]="langues" [height]="410">
            <kendo-grid-column field="Id" title="ID" width="40">
            </kendo-grid-column>
            <kendo-grid-column field="cod" title="Code" width="40">
            </kendo-grid-column>
            <kendo-grid-column field="des" title="Description" width="60">
            </kendo-grid-column>
            <kendo-grid-column field="cod1" title="code 1" width="80">
            </kendo-grid-column>
            <kendo-grid-column field="cod2" title="code 2" width="80">
            </kendo-grid-column>
            <kendo-grid-column field="dat1" title="date 1" width="80">
            </kendo-grid-column>
            <kendo-grid-column field="dat1" title="date 2" width="80">
            </kendo-grid-column>
            <kendo-grid-column title="Opération" width="120">
                <ng-template kendoGridCellTemplate column="column" let-dataItem let-columnIndex="columnIndex" >
                    <button (click)="modification(dataItem)">Modifier</button>
                    <button (click)="delete(dataItem)">Supprimer</button>
                    <button (click)="detailLangue(dataItem)">Consulter</button>
                </ng-template>
            </kendo-grid-column>
 </kendo-grid>
 <app-langue-details [langue]="selectedLangue"></app-langue-details>
 <app-update-langue [langue]="modifedLangue"></app-update-langue>

It's my It's my update-lang.component.html 是我的,这是我的update-lang.component.html

<h2>Modification de la langue</h2>
<div *ngIf="langue">
<form>
<table>
  <!-- <tr>
      <td>Id</td><td><input name="id" [(ngModel)]="langue.langueId"/></td>
  </tr> -->
  <tr>
      <td>Code</td><td><input name="code" [(ngModel)]="langue.codlan"/></td>
  </tr>
  <tr>  
      <td>des</td><td><input name="des" [(ngModel)]="langue.deslan"/></td>
  </tr>
  <tr>    
      <td>Code1</td><td><input name="code1" [(ngModel)]="langue.codopercrehoro"/></td>
  </tr>
  <tr>    
      <td>Code2</td><td><input name="code2" [(ngModel)]="langue.codopermajhoro"/></td>
  </tr>
  <!--<tr>  
      <td>T1</td><td><input type="datetime-local" name="date1"  [(ngModel)]="langue.dattimcrehoro"/></td>
  </tr>
  <tr>
      <td>T2 </td><td><input type="datetime-local" name="date2" [(ngModel)]="langue.dattimmajhoro"/></td>
  </tr>-->
  <tr>
        <td></td><td><button (click)="updateLangue()">Enregistrer</button></td>
  </tr>
</table>
</form> 

</div>

It's my file configuration config.service.ts 这是我的文件配置config.service.ts

import {Injectable} from '@angular/core';
import {Http, Headers, Response, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

/**
 *  Service permettant de mettre en commun des fonctions utilisées dans toute l'application
 */

@Injectable()
export class AppSettingsService {
  settings: Observable<any>;
  currentUser: any;
  toasterTradMessage: string;

  constructor(
    private http: Http,
  ) {
    this.settings = this.http.get("../../assets/appsettings.json")
      .map(this.extractData)
      .catch(this.handleErrors);
  }

  /**
  * Fonction de recuperation du lien vers l'API contenu dans le json assets/appsettings.json
  * Retour : json avec lien vers API (settings.pathAPI)
  *
  */
  getSettings(): Observable<any> {
    return this.settings;
  }

  private extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  private handleErrors(error: any): Observable<any> {
    console.error(error);
    return Observable.throw(error.message || error);
  }
}

It's my entity lange.ts 这是我的实体lange.ts

export class Langue {
  Id: number;
  cod: string;
  des: string;
  cod1: string;
  cod2: string;
  dat1: null;
  dat2: null;
}

Please, Can you help me because it's important, it's the first time I'm having these problems, that's why I'm in trouble. 拜托,您能帮我吗,因为这很重要,这是我第一次遇到这些问题,这就是我遇到麻烦的原因。

Your request to a different domain(localhost in your case) then your page is on. 您请求到另一个域(在您的情况下为localhost),则页面打开。 So the browser is blocking it as it usually allows a request in the same origin for security reasons. 因此,由于安全原因,浏览器通常会阻止来自同一来源的请求,因此阻止了它。

http://localhost:8081/APIRest/resources/langue/update: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had http://localhost:8081/APIRest/resources/langue/update: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 500. http://localhost:8081/APIRest/resources/langue/update: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP状态码为500。

If you closely look at the URL you will find that the port numbers for the same hosts are varying. 如果仔细查看URL,您会发现相同主机的端口号在变化。

Update: Refer to the following link: 更新:请参阅以下链接:

Why does my JavaScript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not? 为什么Postman没有,我的JavaScript为什么会出现“请求资源上没有'Access-Control-Allow-Origin'标头”错误?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM