"Web Api在Postman中可以插入正常工作,但在代码中无法运行。"
"Web Api在Postman中可以插入正常工作,但在代码中无法运行。"
这个问题已经有了答案:
以下的简单插入记录方法在Postman中运行,但我无法让它在我的AngularJS控制器中运行。
Postman Headers (Post) Key ContactID Value 0 Key FName Value John Key LName Value Smith Key Cache-Control Value no-cache Key Content-Type Value application/x-www-form-urlencoded
$scope.insert = function () { var obj = { "ContactID": 0, "FName": "John", "LName": "Smith" }; var url = "http://********************.net/api/create"; $http({ method: 'POST', url: url, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, dataType: 'json', contentType: 'application/json', data: obj }); }
admin 更改状态以发布 2023年5月24日
使用AngularJS服务进行URL编码变量
在AngularJS 1.4及以上版本中,可以使用两个服务处理POST请求的URL编码数据的过程,从而无需使用transformRequest
操作数据或使用外部依赖项(如jQuery):
-
$httpParamSerializerJQLike
- 受jQuery的.param()
启发的序列化器 -
$httpParamSerializer
- Angular本身用于GET请求的序列化器
示例用法
$http({ url: 'some/api/endpoint', method: 'POST', data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller headers: { 'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header } }).then(function(response) { /* do something here */ });