缺少必需的请求正文:前端请求问题

时间:2018-04-19 09:22:17

标签: angular typescript spring-mvc angular4-forms

我发出了一个POST请求,要求从我的项目后端向数据库添加一个新实体 我在邮递员身上测试了它,效果很好

但是当我尝试从前端UI添加一个新实体(我使用角度4)时出现此错误:缺少必需的请求体:

无法加载资源:服务器响应状态为500(Erreur Interne de Servlet)

我猜我的打字稿代码有问题 有人可以帮我吗?

<form (ngSubmit)="createEntity()">
    <div class="form-group">
      <label for="code">Code</label>
      <input type="text" [(ngModel)]="code" placeholder="Code" name="code" class="form-control" id="code">
    </div>
    <div class="form-group">
      <label for="description">Description</label>
      <input [(ngModel)]="description" placeholder="Description" name="description" class="form-control" id="description">
    </div>
    <div  class="form-group">
       <label for="type">Type</label>
      <p-dropdown [(ngModel)]="type" [options]="entityTypes" filter="filter" name="type" placeholder="Type" [style]="{'width':'100%'}">
      </p-dropdown>
    </div>  
        <div  class="form-group">
       <label for="numero">Profil</label>
       <p-dropdown [(ngModel)]="profil" [options]="entityProfiles" filter="filter" name="profil" placeholder="Profil" [style]="{'width':'100%'}">
      </p-dropdown> 
    </div>
    <div class="form-group">
      <label for="number">number</label>
      <input [(ngModel)]="number" placeholder="number" name="number" class="form-control" id="number">
    </div>
    <button type="submit" class="btn btn-success">Valider</button>
  </form>


        

entity: Entity;

export interface Entity {
  id?: string;
  code?: string;
  description?: string;
  type?: string;
  number?: string;
  profil?: string;
}  


createEntity(): void {
        this.EntitySRV.CreateEntity(this.entity)
            .subscribe(data => {
                alert("Entity created successfully.");
            });
    }; 

// entity service .ts
CreateEntity(entity) {
    const entityUrl = this._entity;
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Access-Control-Allow-Headers', 'Content-Type, Accept');
    return this.http.post(entityUrl, entity, { headers })
        .map(res => {
            return res.json();
        })
        .catch(this.handleError);
}

    //RestController : 
     @PostMapping
        public Entite create(@RequestBody Entite entite){
            return entityService.create(entite);
        }


 //Service     
    @Override
    public Entite create(Entite entite) {
    entityDao.persist(entite);
    return entite;
            }

 // DAO 

    private static final String QUERY_SAVE_ENTITY           = " INSERT INTO Entite(code, description, numero, profil,type)";

        @Override
        public Entite saveEntity() {
        return (Entite) executeQuery(QUERY_SAVE_ENTITY);
    }

提前谢谢你:)

3 个答案:

答案 0 :(得分:0)

这是我的服务和组件功能,我认为它对您有所帮助。

  

Appservice.ts文件

        import { Injectable } from '@angular/core';
        import { Http, Response, ResponseContentType } from '@angular/http';
        import { Observable } from 'rxjs/Observable';
        import { Jsonp, URLSearchParams } from '@angular/http';
        import { Headers, RequestOptions } from '@angular/http';
        import 'rxjs/add/observable/throw';
        import 'rxjs/add/operator/catch';
        import 'rxjs/add/operator/map';
        import { HttpHeaders } from '@angular/common/http';
        @Injectable()
        export class AppService {
            utcOffset = -(new Date().getTimezoneOffset());
            private CONTENT_TYPE_JSON = 'application/json';
            private CONTENT_TYPE_FORM_DATA = 'application/x-www-form-urlencoded';
            private ACCEPT = 'application/json';
            private UTC_OFFSET;
            private PLATFORM = 'WEB';
            private APP_VERSION = '1.00';
            private VERSION = '1.0';

            constructor(private http: Http) {
                const offset = this.utcOffset / 60;
                this.UTC_OFFSET = offset.toString();
            }

            postJSONData(apiUrl: string, value: Object): Observable<any> {
                const body = value;
                const headers = new Headers();
                headers.append('Content-Type', this.CONTENT_TYPE_JSON);
                headers.append('utc-offset', this.UTC_OFFSET);
                headers.append('platform', this.PLATFORM);
                headers.append('app-version', this.APP_VERSION);
                headers.append('version', this.VERSION);
                headers.append('accept', this.ACCEPT);
                if (localStorage.getItem('userData')) {
                const user = JSON.parse(localStorage.getItem('userData'));
                headers.append('token', user.token);
                headers.append('session', user.session);
                }
                return this.http.post(apiUrl, body, { headers: headers })
                .map(this.extractData)
                .catch(this.handleServerError);
            }

            private extractData(res: Response) {
                    let body = res.json();
                    var headers = res.headers;
                    if (body.status == 500) {
                    let error = body;
                    let errMsg = (error.msg) ? error.msg : ((error.status) ? `${error.status} - ${error.statusText}` : 'Request error');
                    }
                    return body || {};
            }
            private handleServerError(error: any) {
                    const defaultErrorMsg = 'Internal server error, please try again';
                    const customError = 'Could not connect to the server. Please try again later';
                    // `${error.status} - ${error.statusText}`
                    const errMsg = (error.message) ? error.message : ((error.status) ? customError  : defaultErrorMsg);
                    return Observable.throw(errMsg);
            }
        }
  

功能

   this.appService.postJSONData(URL, data).subscribe(result => {
            console.log(result);
            }, err => {
                console.log(err);
            });

答案 1 :(得分:0)

当我用httpClient替换http时: 同样的错误:

HttpErrorResponse 错误 : {code:null,message:“缺少必需的请求体:public com .... reate(com.model.persistent.Entite)”} 头 : HttpHeaders {normalizedNames:Map(0),lazyUpdate:null,lazyInit:ƒ} 信息 : “http://localhost:4200/project-core/entity/的Http失败响应:500 Erreur Interne de Servlet” 名称 : “HttpErrorResponse” 好 : 假 状态 : 500 状态文本 : “Erreur Interne de Servlet” 网址 : “http://localhost:4200/project-core/entity/” 的 : HttpResponseBase

答案 2 :(得分:0)

问题已解决:)

解决方案: 我使用HttpClient而不是旧的http 编辑我的代码如下:

   //service
   CreateEntity(entite) {
        const entityUrl = this._entity;
        return this.httpc.post(entityUrl, entite);
    }
    
    
   //ts
   
   entite = new Entite();
   
    createEntity(): void {
    
        this.EntitySRV.CreateEntity(this.entite)
            .subscribe(data => {
                 this.submitted = true;
            });
    }  
    
    
   
    
  <form>
    <div class="form-group">
      <label for="code">Code</label>
      <input type="text" [(ngModel)]="entite.code" placeholder="Code" name="code" class="form-control" id="code">
    </div>
    <div class="form-group">
      <label for="description">Description</label>
      <input [(ngModel)]="entite.description" placeholder="Description" name="description" class="form-control" id="description">
    </div>
    <div  class="form-group">
       <label for="numero">Type</label>
      <p-dropdown [(ngModel)]="entite.type" [options]="entityTypes" filter="filter" name="type" placeholder="Type" [style]="{'width':'100%'}">
      </p-dropdown>
    </div>  
        <div  class="form-group">
       <label for="numero">Profil</label>
       <p-dropdown [(ngModel)]="entite.profil" [options]="entityProfiles" filter="filter" name="profil" placeholder="Profil" [style]="{'width':'100%'}">
      </p-dropdown> 
    </div>
    <div class="form-group">
      <label for="numero">Numero</label>
      <input [(ngModel)]="entite.numero" placeholder="numero" name="numero" class="form-control" id="numero">
    </div>
    <!-- removed the type="button" cuz it didn"t let the (click) do its job ;) -->
    
    <button (click)="createEntity()" class="btn btn-success">Valider</button>
  </form>

TADAAA:D