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());
}
}