简单地说,在我的Web应用程序方面,我向运行HttpListener的C#应用程序发布了一些数据,这个请求被Listener捕获,然后完成了一些操作,最后向Web应用程序发送了一个响应以响应原始帖子。
以下是侦听器捕获请求后使用的回调方法
private void ListenerCallback(IAsyncResult listenerresult)
{
var context = listener.EndGetContext(listenerresult);
Thread.Sleep(1000);
var data_text = new StreamReader(context.Request.InputStream,
context.Request.ContentEncoding).ReadToEnd();
//Do some work and create the 'responseArray' that is sent back containing some message
var response = context.Response;
response.ContentLength64 = responseArray.Length;
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Access-Control-Allow-Methods", "POST, GET");
response.StatusCode = 200;
response.StatusDescription = "OK";
response.OutputStream.Write(responseArray, 0, responseArray.Length);
response.OutputStream.Close();
}
当我使用jQueryAjax Post到达侦听器并向其发送一些数据时,它工作得很好,并且变量data_text
填充了我发送的内容。这是我使用的Ajax Post:
jQuery.ajax({
type: "POST",
url: 'http://127.0.0.1:8089/',
data: '{"Variable 1":"Value 1", "Variable 2":"Value 2"}',
crossDomain: true,
success: function (data) {
// Use data here
}
}).fail(function (jqXHR, textStatus, errorThrown) {
alert('Alert user that something went wrong');
});
我现在必须将我的实现转移到angular,这就是问题的根源。当使用angular的$http.post时,Listner确实捕获了请求,但data_text变量总是空的,即从请求的数据流中读取的数据是空的。这是我使用的$http.post-注意:在使用Angular的post:时,我使用了一个封装$http.post的服务来节省时间
httpService.post('http://127.0.0.1:8089/', data).then(function (result) {
alert(result.msg);
});
这里是用于执行上面显示的帖子的服务:
app.service('httpService', function($http, $q) {
this.post = function (url, data) {
try {
return $http.post(url, data || {}, { timeout: 1000 * 20 }).then(function (response) {
if (response.data.success) {
return response.data.obj;
} else {
return ($q.reject(response.data.msg));
}
}, function (error) {
if (error.status === 0) {
return ($q.reject('408' + ' : The server timed out waiting for the request, please try again'));
}
return ($q.reject(error.status + ' : ' + error.statusText));
});
} catch (e) {
alert(e.message);
return $q.reject(e.message);
}
}
});
据我所知,Angular是在jQuery的精简版本之上构建的,当你到达最低级别(vanillaJS)时,jQueryAjax Post正在做与$http.Post相同的事情。我缺少什么?
更新:正如Mike Feltman所指出的,我可以在我的数据上使用$httpParamSerializerJQLike,并在标题中指定内容类型:
return $http.post(url, $httpParamSerializerJQLike(data), { headers: { 'Content-type': 'application/x-www-form-urlencoded'}})
这很有效,我收到了数据,但在我无法使用的格式中,我需要JSON格式的数据,所以我读了一点,并将内容类型从application/x-www-form-urlencoded
更改为application/json
,但之后我再次没有收到数据。
Angular与Jquery发送post数据的方式可能存在差异。为了解决这个问题,你必须将$httpParamSerializerJQLike注入到你的服务中,然后指定在对http.post的调用中使用它,方法是将你的数据发送到一个类似于$httpParam串行化器JQLike(myData)的调用中。
这是上面有棱角的文档:https://docs.angularjs.org/api/ng/service/$httpParamSerializerJQLike
我有一个工作样本,我现在无法找到,但如果这还不足以让你继续下去,可以稍后再挖。
我在我的服务中遇到了一些问题,让它正常运行,由于我也包装了$http,我使用了这样的东西:
var transport = $httpParamSerializerJQLike(data);
return $http.post(url, transport, { headers: { 'Content-type': 'application/x-www-form-urlencoded'}})