简体   繁体   English

在 html 按钮上使用 javascript 将 json 数据发送到托管的 python flask api 单击并在 HTML 标签上打印来自 API 的响应

[英]Send json data to hosted python flask api using javascript on html button click and printing the response from API on a HTML label

I've hosted a python flask api on pythonanywhere.我在 pythonanywhere 上托管了一个 python flask api。 It takes json input, performs some operations and returns response in json format.它接受 json 输入,执行一些操作并以 json 格式返回响应。

I've a website that tries to call this API and should display the response.我有一个网站试图调用这个 API 并且应该显示响应。

Button click calls a javascript function apicall().按钮单击调用 javascript 函数 apicall()。

HTML code: HTML代码:

<button type="submit" name = "submit" id = "submit" onclick="apicall()">Check</button>
<label id="response"></label>

Javascript Function (It tries to set the label text to the response text): Javascript 函数(它尝试将标签文本设置为响应文本):

<script type="text/javascript">
function apicall(){ 

  xmlObj = new XMLHttpRequest(); //suddenly global scope
  xmlObj.open("POST","http://abc.pythonanywhere.com/xyz",true);
  xmlObj.setRequestHeader("Content-Type", "application/json");
  var website=document.getElementById("url").value;
  var data = JSON.stringify({"url": website});
  xmlObj.send(data);
  xmlObj.onreadystatechange = handleRequestStateChange();
  function handleRequestStateChange(){  
  alert("here");
  if(xmlObj.readyState == 4 && xmlObj.status==200){
    var json = JSON.parse(xmlObj.responseText);
    document.getElementById("response").innerHTML =json.prediction;
    alert("if loaded");
  }
  else
  {
      alert(xmlObj.status);
  }
 }
}
</script>

However, it alerts status 0.但是,它会警告状态 0。

Error printed on console says: "[CORS]The origin did not find the origin in the access-control-allow-origin in the request header for cross-origin resource at http://abc.pythonanywhere.com/xyz "控制台上打印的错误说:“[CORS]源在http://abc.pythonanywhere.com/xyz 的跨源资源请求标头中的 access-control-allow-origin 中找不到源”

Network Tab in developer tools shows the connection to python anywhere and response code of 200[ok]开发人员工具中的网络选项卡显示了在任何地方与 python 的连接以及 200[ok] 的响应代码

Referred links:参考链接:

Why is AJAX returning HTTP status code 0? 为什么 AJAX 返回 HTTP 状态代码 0?

XMLHttpRequest status 0 (responseText is empty) XMLHttpRequest 状态 0(响应文本为空)

But was not able to solve the issue但无法解决问题

I also tried jquery to do the same thing我也试过 jquery 做同样的事情

<script>
        $(document).ready( function() {
        $('#submit').click(function() {
           var website=document.getElementById("url").value;
           $.ajax({
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(website),
                dataType: 'json',
                url: 'http://abc.pythonanywhere.com/xyz',
                success: function (e) {
                   alert(e);
                   console.log(e);
                   window.location = "https://www.google.com"
                },
                error: function(error) {
                console.log(error);
            }
            });
        });
  });
</script>

But the jquery code just reloads the page when I click that button with no errors anywhere(or maybe the error log and network log just clears up because of reload).但是当我单击该按钮时,jquery 代码只是重新加载页面而没有任何错误(或者错误日志和网络日志可能只是因为重新加载而清除)。

How can I allow the cross origin requests on python API or how do change the code in javascript or jquery to make this thing work?如何允许 python API 上的跨源请求,或者如何更改 javascript 或 jquery 中的代码以使这件事起作用?

I was able to solve this issue by adding the following lines to python rest API.通过将以下几行添加到 python rest API,我能够解决这个问题。

pip install -U flask-cors pip install -U flask-cors

from flask_cors import CORS
cors = CORS(app)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM