AngularJS跨域使用POST方式请求后端接口

 

0.背景

AngularJS跨域请求接口一般都是使用jsonp。

前端例如下面这样:

$http.jsonp(url).success(function(response){
    callback(response);
});

可以把参数拼接到URL中,例如?name=hello&user=cc 这样

 

后端接口类似如下:

/**
 * 新增
 *
 * @return
 */
@RequestMapping(value = "create", method = {RequestMethod.GET, RequestMethod.POST})
public BaseResult<Object> create(String name, String reason, String batch, Integer batchProvideTimeout, HttpServletRequest request) {
    try {
        Map<String, Object> map = new HashMap<>(3);
        map.put("affectedRow", 0);
        return new BaseResult<Object>(true, map);
    } catch (Exception e) {
        logger.error("errorMessage={}", e.getMessage(), e);
        return new BaseResult<Object>(false, 200, e.getMessage());
    }

这样开发比较简单,但是所有接口都是GET的方式,不太符合HTTP规范。而且每个参数都需要写到后端接口方法参数中。如果想使用POST请求接口,可以按照如下方式。

 

1.前端AngularJS请求

 

//使用transformRequest,加上"application/x-www-form-urlencoded",服务端不要使用@RequestBody,才可以使用post传参成功
$http({
    method:'post',
    url:'http://localhost:7001/taskVipWorksheet/postCreate?reason=1&id=0',
    headers:{"Content-Type":"application/x-www-form-urlencoded"},
    //headers:{"Content-Type":"application/json;charset=UTF-8"},
    data:{"name":"hello","createUser":"cc"},
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj){
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
        return str.join("&");
    }
}).success(function(response){
    var data = response;
    alert("alert成功");
    callback(data);
});

 

2.后端接口

/**
   * 注意,参数VipWorksheetBean前面不能加@RequestBody,否则获取不到数据
   *
   * @return
   */
  @Deprecated
  @RequestMapping(value = "postCreate", method = RequestMethod.POST)
  public BaseResult<Object> postCreate(VipWorksheetBean vipWorksheetBean, HttpServletRequest request) {
      try {
          Map<String, String> paramMap = new HashMap<>();
          Enumeration<String> es = request.getParameterNames();
          while (es.hasMoreElements()) {
              String s = es.nextElement();
          }
          Map<String, Object> map = new HashMap<>(3);
          map.put("paramMap", paramMap);
          return new BaseResult<Object>(true, map);
      } catch (Exception e) {
          logger.error("errorMessage={}", e.getMessage(), e);
          return new BaseResult<Object>(false, 200, e.getMessage());
      }
  }

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值