![](/img/trans.png)
[英]How to retrieve data from a RESTful service as a post request in angular js?
[英]Error Calling a WCF POST Restful Service from Angular JS
我陷入了一个奇怪的问题,即我从AngularJS代码获得的GET WCF Restful API可以正常工作,但POST请求不起作用。 以下是我的WCF邮政服务代码:
接口代码和实现:
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "TestPost")]
string TestPost(string sValue);
public string TestPost(string sValue)
{
return sValue;
}
Angular JS客户端代码:
$scope.testPostAPI = function ()
{
var data = $.param(
{
FName: "John",
LName: "Smith"
});
var config =
{
headers:
{
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post('http://localhost:5000/RestServiceImpl.svc/TestPost', data, config)
.success(
function (data, status, headers, config)
{
$scope.DOCUMENTSAVERESPONSE = data;
$scope.ResponseDetails= 'Response from post service'
})
.error(function (data, status, header, config)
{
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
}
您正在将复杂类型从客户端传递给期望简单类型的指定点。 您有两个选择。
1将“ John Smith”发送为简单的类型字符串。
2在api方法上更改您的形式参数以采用Person,例如:
public class Person
{
public string FName{get;set;}
public string LName{get;set;}
}
public Person TestPost(Person sValue)
{
...
}
使用内容类型为:application / json,然后在传递数据值之前使用JSON.stringify(data)
$ http.post(' http:// localhost:5000 / RestServiceImpl.svc / TestPost ',JSON.stringify(data),config).success(函数(data,status,headers,config){
$ scope.DOCUMENTSAVERESPONSE =数据;
$ scope.ResponseDetails ='来自邮局的响应'}).error(函数(数据,状态,标题,配置){$ scope.ResponseDetails =“ Data:” + data +“
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.