使用URL作为字符串的POST会被烧瓶

时间:2015-10-01 23:47:31

标签: javascript python flask

我使用跨源资源共享(CORS)AJAX请求进行了chrome扩展。它正在与烧瓶上的REST api交谈。它将URL作为字符串POST(如send()中所示)。然后我试图让烧瓶将URL保存为字符串,但它非常奇怪地解释了URL。现在我只想将一个名为“url”的局部变量保存为发布的URL的字符串。

Flask代码:

for items in request.form:
      url = items
      break
 print str(request.form)
 print str(url)

命令行输出:

ImmutableMultiDict([('redirect', u'true'), ('http://www.amazon.com/gp/product/B00KHWSB5M?gwSec', u'1'), ('ref_',
 u's9_simh_gw_p74_d15_i2')])
redirect

的Javascript / AJAX:

  var xhr = new XMLHttpRequest();
  xhr.open('POST', url, true);
  xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  xhr.onload = function() {
    var text = xhr.responseText;
    var title = text; //getTitle(text);
    alert('Response from CORS request to ' + url + ': ' + title);

  };
  xhr.send("http://www.amazon.com/gp/product/B00KHWSB5M?gwSec=1&redirect=true&ref_=s9_simh_gw_p74_d15_i2");

堆栈溢出正在改变send函数中的url。这是:http://www.amazon.com/gp/product/B00KHWSB5M?gwSec=1&redirect=true&ref_=s9_simh_gw_p74_d15_i2

1 个答案:

答案 0 :(得分:2)

我在客户端看到了两个问题。

首先,您要提交一个表单,该表单应该是一组键/值对。如果你需要发送一个网址,那么更有意义的是使用这种语法:

url=http://www.amazon.com/...

然后在Flask一侧,您可以使用以下网址获取此网址:

url = request.form['url']

但在你准备好这样做之前,你必须考虑角色转义的第二个问题。 application/x-www-form-urlencoded内容类型要求表单字段的值经过URL编码,以便服务器正确解释。以下是您在问题中指定的URL在编码时的外观:

http%3A%2F%2Fwww.amazon.com%2Fgp%2Fproduct%2FB00KHWSB5M%3FgwSec%3D1%26redirect%3Dtrue%26ref_%3Ds9_simh_gw_p74_d15_i2

您可以使用函数encodeURIComponent生成此编码。

根据我提到的两项更改,您的send()电话会议如下:

xhr.send("url=" + encodeURIComponent("http://www.amazon.com/..."));
相关问题