簡體   English   中英

錯誤500后球衣

[英]Error 500 post angular jersey

我在球衣充實方面有問題。 當我執行更新操作時,eclipse的控制台和瀏覽器的控制台顯示錯誤。

對於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)

對於瀏覽器的控制台,錯誤是:

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

這是我的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();
        }

    }

這是我的其余代碼

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

這是我的角度代碼服務

    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());
      }
    }

這是我的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);
               }
    );
  }

}

這是我的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);
         }
      );
    }
  }
}

這是我的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>

是我的,這是我的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>

這是我的文件配置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);
  }
}

這是我的實體lange.ts

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

拜托,您能幫我嗎,因為這很重要,這是我第一次遇到這些問題,這就是我遇到麻煩的原因。

您請求到另一個域(在您的情況下為localhost),則頁面打開。 因此,由於安全原因,瀏覽器通常會阻止來自同一來源的請求,因此阻止了它。

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狀態碼為500。

如果仔細查看URL,您會發現相同主機的端口號在變化。

更新:請參閱以下鏈接:

為什么Postman沒有,我的JavaScript為什么會出現“請求資源上沒有'Access-Control-Allow-Origin'標頭”錯誤?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM