Angular,内容类型不与$ http一起发送

rao*_*sto 59 angularjs

Angular没有添加正确的内容类型选项,我尝试了以下命令:

$http({
    url: "http://localhost:8080/example/teste",
    dataType: "json",
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    }
}).success(function(response){
    $scope.response = response;
}).error(function(error){
    $scope.error = error;
});
Run Code Online (Sandbox Code Playgroud)

上面的代码生成以下http请求:

POST http://localhost:8080/example/teste HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 0
Cache-Control: no-cache
Pragma: no-cache
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
Content-Type: application/xml
Accept: application/json, text/plain, */*
X-Requested-With: XMLHttpRequest
Referer: http://localhost:8080/example/index
Accept-Encoding: gzip,deflate,sdch
Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: JSESSIONID=C404CE2DA653136971DD1A3C3EB3725B
Run Code Online (Sandbox Code Playgroud)

如您所见,内容类型不是"application/json",而是"application/xml".我在这里错过了什么吗?

Jos*_*Lee 91

您需要在请求中包含一个正文.Angular会删除内容类型标头.

添加data: ''到参数中$http.

  • 但是如果我想将对象作为数据发送怎么办?我正在使用ASP.NET Generic HTTP处理程序,由于某种原因,`context.Request.Params ["formData"]`不起作用,但StackOverflow帖子让我使用`string json = new StreamReader(context. Request.InputStream).ReadToEnd();`有效,但我并不完全放心使用它,因为我宁愿按名称访问提交的请求参数值. (3认同)
  • 上帝,这是一个救命!这是默认的HTTP协议行为还是Angular $ http行为? (2认同)

fcm*_*fcm 30

$http({
    url: 'http://localhost:8080/example/teste',
    dataType: 'json',
    method: 'POST',
    data: '',
    headers: {
        "Content-Type": "application/json"
    }

}).success(function(response){
    $scope.response = response;
}).error(function(error){
    $scope.error = error;
});
Run Code Online (Sandbox Code Playgroud)

试试这样吧.

  • 我担心它在Angular 1.3.14中不起作用,如果没有`data`,`Content-Type`就被删除了.空`data`参数解决了这个问题... (3认同)