【问题标题】:AngularJS $http.post data doesn't get to serverAngularJS $http.post 数据没有到达服务器
【发布时间】:2015-05-15 16:21:11
【问题描述】:

我刚刚开始构建我的第一个 angularjs 项目,但我被 $http.post 卡住了。无论我发送什么数据,它都不会被服务器(Django)拦截。我看过很多帖子说我必须将 Content-Type 标题更改为:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

这样做了,没有帮助。

当我开始深入研究,比较$http和Jquery的$.post时,我注意到当用$http发送数据时,这是发送的Form Data:

{"first_prop":"789564","second_prop":"Foo","third_prop":"Bar"}:

以分号结尾。

当我使用 $.post 发送它(并且它有效)时,这就是发送的内容:

first_prop:789564
second_prop:Foo
third_prop:Bar

因此,他们发送信息的方式不同。

有人知道我在 $http.post 上做错了什么吗?

这是我的代码:

$http.post('pakashnotifier/addSlave', {
first_prop:"789564",
second_prop:"Foo",
third_prop:"Bar"
})

更新 我现在注意到,使用 $http.post,帖子在服务器上被截获为 GET。

如果有人能帮忙,那就太好了:)

【问题讨论】:

    标签: jquery django angularjs http-post


    【解决方案1】:

    首先,$http 中的默认转换使用 JSON。您可以在 API 文档$http 中的“默认转换”中查看此项,如果需要接受application/x-www-form-urlencoded 格式,则需要根据您的服务器进行设置。

    然后这是我在 Chrome DevTools 中找到的表单数据:

    {"first_prop":"789564","second_prop":"Foo","third_prop":"Bar"}
    

    我没有得到最后的分号。

    【讨论】:

      【解决方案2】:

      你应该试试这个

      $http.post('pakashnotifier/addSlave', {
          data : {
              first_prop:"789564",
              second_prop:"Foo",
              third_prop:"Bar"
          }
      })
      

      如果使用 django,似乎可以使用 jquery $param

      $http({ 
          method: 'POST', 
          url: '/url/', 
          data: $.param({
              first_prop:"789564",
              second_prop:"Foo",
              third_prop:"Bar"
          })
      })
      

      【讨论】:

      • 试过了,但没有用,我现在注意到请求是作为 POST 发送的,但 django 将其作为 GET 接收。
      • 更新了与 django 匹配的答案。这应该工作
      • 谢谢!这有很大帮助。奇怪的是,$http.post 有时会被截获为 GET 帖子和 POST。无论如何,它也永远不会作为 ajax 请求被拦截
      • @sid802 你说有时 POST 请求作为 GET 接收。我似乎有同样的问题,你知道我们为什么会这样吗?更好的是,如何解决它? :P
      • @sid802 你说有时 POST 请求作为 GET 接收。我似乎有同样的问题,你知道我们为什么会这样吗?更好的是,如何解决它? :P
      猜你喜欢
      • 1970-01-01
      • 2022-10-04
      • 2017-09-20
      • 2016-11-22
      • 1970-01-01
      • 2016-02-19
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多