如何在http.post的URL参数中传递#、^等特殊字符以避免请求错误?
解决POST请求URL参数含特殊字符导致的Bad Request问题
这问题我之前踩过坑!本质是你直接把带特殊字符的参数拼到URL里,这些字符(比如#、^)属于URL的保留/特殊字符,浏览器或服务器解析时会把它们当成URL结构的一部分,而非参数值,自然就返回"bad request"了。下面给你两种靠谱的解决办法:
方法1:对每个参数值单独做URL编码
用JavaScript的encodeURIComponent()方法把每个参数值转成URL安全的编码格式,它会把#转成%23、^转成%5E,彻底避免解析错误。修改后的代码如下:
$http.post("requestFormDataInsert.jsp?manager=" + encodeURIComponent($scope.managerName) + "&productName=" + encodeURIComponent($scope.productName) + "&productVersion=" + encodeURIComponent($scope.versionNumber) + "&expectedDate=" + encodeURIComponent($("#datepicker1").val()) + "&description=" + encodeURIComponent($scope.description) + "&requestType=" + encodeURIComponent($scope.requestType) ).then( function( resp ){ $scope.requestId = resp.data; alert("Your response has been updated successfully") $location.path('/'); });
注意:别用
encodeURI()代替,它不会编码#、^这类特殊字符,解决不了你的问题。
方法2:把参数放到POST请求体里(更推荐)
既然是POST请求,本来就不该把参数拼在URL上——这既不符合POST的语义,也容易暴露参数(尤其是敏感内容)。把参数放到请求体里,Angular会自动帮你处理编码问题,后端只需要从请求体读取参数即可。修改后的代码示例:
// 先把参数整理成对象 var postData = { manager: $scope.managerName, productName: $scope.productName, productVersion: $scope.versionNumber, expectedDate: $("#datepicker1").val(), description: $scope.description, requestType: $scope.requestType }; // POST请求时把对象作为第二个参数传入(请求体) $http.post("requestFormDataInsert.jsp", postData).then( function( resp ){ $scope.requestId = resp.data; alert("Your response has been updated successfully") $location.path('/'); });
这里需要注意:后端要对应调整参数获取方式。比如Java后端,如果用Spring的话,可以用
@RequestBody注解接收JSON格式的参数;如果后端期望表单格式,可以配置Angular的$http用application/x-www-form-urlencoded编码请求体。
内容的提问来源于stack exchange,提问作者Nishant Singh
相关产品推荐
相关产品推荐

