缺少必需的请求正文:前端请求问题
Required request body is missing : front request issues
我发出 POST 请求从我的项目后端向数据库添加一个新实体
我在 postman 上测试过,效果很好
但是当我尝试从前面添加一个新实体时 UI(我正在使用 angular 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);
}
提前谢谢你:)
这是我的服务和组件功能,我认为它会对您有所帮助。
Appservice.ts file
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);
}
}
Function
this.appService.postJSONData(URL, data).subscribe(result => {
console.log(result);
}, err => {
console.log(err);
});
问题已解决:)
解决方案:
我使用 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
我发出 POST 请求从我的项目后端向数据库添加一个新实体 我在 postman 上测试过,效果很好
但是当我尝试从前面添加一个新实体时 UI(我正在使用 angular 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);
}
提前谢谢你:)
这是我的服务和组件功能,我认为它会对您有所帮助。
Appservice.ts file
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);
}
}
Function
this.appService.postJSONData(URL, data).subscribe(result => {
console.log(result);
}, err => {
console.log(err);
});
问题已解决:)
解决方案: 我使用 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