Solve problems Ionic5 / Angular8 used in the project Angular the HttpClient to send post request invalid

Solve problems Ionic5 / Angular8 used in the project Angular the HttpClient.post request invalid


Solutions directly on the
1, written java server interface

	@Description("获取计划执行监控总体数据列表")
	@POST
	@Path("/getPlanExecMonitorTotalData")
	@Produces(MediaType.APPLICATION_JSON)
	public String getPlanExecMonitorTotalData(
			@FormParam("dsType") @DefaultValue("demoDs") String dsType,
			@FormParam("planDate") String planDate,
			@FormParam("equipGroupId") String equipGroupId,
			@FormParam("equipJson") String equipJson) {
		
	}

java server POST request interface points

Key 1: add annotations @Produces (MediaType.APPLICATION_JSON) on the interface methods.
Key 2: annotate method parameters @FormParam.

2, the front end wording

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { EnvService } from '../../wongoing/env.service';
import { UtilsService } from '../../wongoing/utils.service';

@Injectable({
  providedIn: 'root'
})
export class JihuaService {

  constructor(private http: HttpClient, private env: EnvService, private utilsService: UtilsService) { }

  /**
   * 获取计划执行监控总体数据列表
   * @param planDate 计划日期
   * @param equipGroupId 生产区域ID
   * @param equipJson 机台列表json串[{equipCode:'', equipName:''}, {equipCode:'', equipName:''}]
   */
  public getPlanExecMonitorTotalData(planDate, equipGroupId, equipJson) {
    const url = this.env.getPlanExecMonitorTotalData;
    const method = 'POST';
    const dsType = this.utilsService.getDataSourceType();
    const usedLanguage = this.utilsService.getUsedLanguage();
    let body = new HttpParams();
    body = body.append('dsType', dsType);
    body = body.append('planDate', planDate);
    body = body.append('equipGroupId', equipGroupId);
    body = body.append('equipJson', equipJson);
    const options = { headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded') };
    // const options = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } };      // 效果等同上一句
    return this.http.post(url, body.toString(), options).toPromise();
  }
}

Key 1: The second parameter format this.http.post body must be param1 = value1 & param2 = value2 this format, as used herein the toString () method HttpParams object into the key parameters such string format.
Key 2: The third parameter to be set this.http.post request header Content-Type is application / x-www-urlencoded.

3, the postman in the test interface
Here Insert Picture Description

Note: it is the Body x-www-form-urlencoded the parameter setting request, instead of form-data set parameters.

Published 138 original articles · won praise 303 · views 120 000 +

Guess you like

Origin blog.csdn.net/zlbdmm/article/details/105356769