【问题标题】:Polymer <core-xhr> - no POST params sentPolymer <core-xhr> - 没有发送 POST 参数
【发布时间】:2015-04-17 08:10:02
【问题描述】:

我正在拼命尝试通过 POST 将数据发送到 express.js 应用程序。 express.js 应用程序工作正常,但无论出于何种原因,POST 数据都没有正确发送到服务器:

var xhrConfig = {
  url: "http://localhost:3000/test",
  body: {"foo": "bar"},
  // body: JSON.stringify({"foo": "bar"}),
  // body: 'foo=bar',
  method: "POST"
};
document.createElement('core-xhr').request(xhrConfig);

我的 express.js console.log(req.body) 输出始终是 {}。无论正文是字符串化的、原始的还是 JSON 发送。我还尝试了 params 而不是 body 只是为了确保。

我在 jQuery 中尝试了相同的方法来排除我的 express.js 路由中存在错误的可能性,但 $.ajax({url: 'http://localhost:3000/test', data: {foo: 'bar'}, type: 'POST'}); 工作得非常好。

那么req,body 总是为空的原因是什么?有什么想法吗?

//编辑:

body: "foo=bar",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},

这个现在可以使用,但是有没有办法可以使用body: {"foo": "bar"} 而不是先将其转换为foo=bar

【问题讨论】:

    标签: post xmlhttprequest polymer


    【解决方案1】:

    据我所知,core-xhr是一个低级元素,它的conf上的body对象不接受JS对象,而是你要使用的字符串body。

    对于您描述的用途,您可以尝试core-ajax,这是一个可以使用对象配置的更高级别的元素。 core-ajax 上的文档:https://www.polymer-project.org/docs/elements/core-elements.html#core-ajax

    <core-ajax
      auto
      url="http://localhost:3000/test"
      body='{"foo": "bar"}'
      handleAs="json"
      method: "POST"
      on-core-response="{{handleResponse}}"></core-ajax>
    

    希望对您有所帮助。如果您需要更详细的示例,请随时询问。

    【讨论】:

      【解决方案2】:

      看起来 express 会查看 Content-Type 标头以确定它具有什么类型的主体,下面对我有用。

      this.$.xhr.request({
          url: "/my/url", 
          method: "POST",
          headers:{
              "Content-Type":"application/json"
          },
          body: JSON.stringify(survey), 
          callback: function(response){
              console.log(response);
          }
      });
      

      【讨论】:

        【解决方案3】:

        我在 Polymer 上也遇到过这个问题。这个问题非常令人沮丧,因为 core-xhr 上没有太多关于 Polymer 的文档。

        由于您自己已经回答了第一个问题,我将回答后者:是/否。如果您查看&lt;core-xhr&gt; 的来源,它只是将参数直接提供给xhr.send(params)。但是,在调用 toQueryString 内部有一个方法,它可以做你想做的事情。

        toQueryString: function(params) {
            var r = [];
            for (var n in params) {
              var v = params[n];
              n = encodeURIComponent(n);
              r.push(v == null ? n : (n + '=' + encodeURIComponent(v)));
            }
            return r.join('&');
          }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-01-24
          • 2011-03-23
          • 1970-01-01
          • 2017-03-02
          • 2017-07-06
          • 2015-07-23
          • 1970-01-01
          • 2012-11-19
          相关资源
          最近更新 更多