使用' application / x-www-form-urlencoded'时,HttpClient post body param无法正确发送。内容类型请求标头

时间:2018-02-22 12:07:11

标签: request http-post httpclient angular5

我使用httpClient发布请求,例如:

我在app.module.js中导入了HttpClientModule,用于http get和post请求。

const httpOptionsWithCookie = {   标题:新的HttpHeaders({'内容类型':' application / x-www-form-urlencoded'}),   withCredentials:true };

this.baseUrl(" API&#34的链接;)

postArguments是一个类似"的对象。 {名称:" XYZ",公司:" ABC"}"

this.http.post(this.baseUrl,postArguments,httpOptionsWithCookie);

我在前端使用angular5,在后端使用spring mvc 我是angular5的新人。

API端代码:

** spring mvc imports

             @RestController
             @RequestMapping(value = "/api/leavePeriod")
             public class LeavePeriodControllerApi {
     private static LogHelper logHelper = LogHelper
        .getInstance(LeaveApplicationControllerApi.class);

    @Autowired
    HttpSession session;

    @Autowired
    Environment env;

    @Autowired
    ILeavePeriodService service;

    @Autowired
    ISecurityCommonService securityCommonService;

    @Autowired
    ILeaveCategoryService leaveCategoryService;

    @Autowired
    ICompanyService companyService;

    @Autowired
    LeavePeriodValidator leavePeriodValidator;

  private User user = new User();
    private String LOGINUSER = "";

 @RequestMapping(value = "/viewLeavePeriod", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object>  viewLeavePeriod( @ModelAttribute LeavePeriodForm form,HttpServletRequest request,@RequestParam(value ="companyId" ,required = false)
    String companyId, @RequestParam(value ="leaveCategoryId", required = false)
    String leaveCategoryId )throws HRAlignBaseException {
     user = (User) session.getAttribute("user");
        LOGINUSER = "LoginUser " + user.getEmpName() + " loginuser empCode "
                + user.getEmpCode();    
        Map<String, Object> returnMap = new HashMap<String, Object>();

     try{
         if(companyId!= null && companyId!="")
         {
             form.setCompanyId(Integer.parseInt(companyId)); 
         }
         if(leaveCategoryId!= null && leaveCategoryId!="")
         {
             form.setLeaveCategoryId(Integer.parseInt(leaveCategoryId));
         }

         returnMap = service.view(form);
         returnMap.put("periodList", form.getLeavePeriodVoList());
         returnMap.put("comId", form.getCompanyId());
         returnMap.put("leaveCatId", form.getLeaveCategoryId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        logHelper
        .info("################"
                + LOGINUSER
                + "############# END Enter LeavePeriodController viewLeavePeriod");
        return returnMap;
    }

}

在angularjs中使用相同的http post请求,但它在angular5中不起作用。

此外,当从ARC执行相同的http帖子时,它工作正常但不适用于angular5

1 个答案:

答案 0 :(得分:1)

用于&#39;内容类型&#39;:&#39; application / x-www-form-urlencoded&#39;表格数据应该像&#34; menuId = 5&amp; buttonRights = adfasdfad&amp; abc = aasdfasdfd&#34;而不是json格式,因此这个功能在angularjs(ngResource)中可用,但在角度5(HttpClient)中不可用。 这是发布数据的标准方式。 下面的代码是针对简单对象的。

   import { URLSearchParams } from "@angular/http"


   testRequest() {
   let data = new URLSearchParams();
    data.append('username', username);
    data.append('password', password);

   this.http
    .post('/api', data)
    .subscribe(data => {
        alert('ok');
     }, error => {
      console.log(error.json());
     });
     }

如果要发布对象或嵌套对象,则必须使用下面的代码手动将对象转换为查询字符串。

       jsonTransformRequest (data) {
          var param = function (obj) {
           var query = '';
        var name, value, fullSubName, subValue, innerObj, i;

     for (name in obj) {
      value = obj[name];

      if (value instanceof Array) {
          for (i = 0; i < value.length; ++i) {
              subValue = value[i];
              fullSubName = name + '[' + i + ']';
              innerObj = {};
              innerObj[fullSubName] = subValue;
              query += param(innerObj) + '&';
          }
      } else if (value instanceof Object) {
          for (let subName in value) {
              subValue = value[subName];
              fullSubName = name + '.' + subName;
              innerObj = {};
              innerObj[fullSubName] = subValue;
              query += param(innerObj) + '&';
          }
      } else if (value !== undefined && value !== null) {
          query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
      }
  }
  return query.length ? query.substr(0, query.length - 1) : query;
      };
       var ret =  (data != null && typeof data === 'object') ? param(data) : 
     data;
      return ret;
     };