Flask 的 XMLHttpRequest GET 缺少输出

Missing output for XMLHttpRequest GET with flask

我开始使用聊天机器人 UI 和 REST API。

我首先用 flask 做了一个简单的 api:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

当我访问 http://EC2_HOSTNAME:5000 时,我可以看到 Hello World!

然后,我将示例从 https://github.com/botui/botui-examples/tree/master/git-stars-bot 改编为简单的 return Hello World!,无论用户输入是什么。

这是我改编的 stars-bot.js 脚本:

var loadingMsgIndex,
    botui = new BotUI('stars-bot'),
    API = 'http://EC2_HOSTNAME:5000';

function sendXHR(repo, cb) {
  var xhr = new XMLHttpRequest();
  var self = this;
  xhr.open('GET', API);
  xhr.onload = function () {
    var res = xhr.responseText
    cb(res);
  }
  xhr.send();
}

function init() {
  botui.message
  .bot({
    delay: 1000,
    content: 'Enter the repo name to see how many stars it have:'
  })
  .then(function () {
    return botui.action.text({
      delay: 1000,
      action: {
        value: 'dummy user input',
        placeholder: 'user input'
      }
    })
  }).then(function (res) {
    loadingMsgIndex = botui.message.bot({
      delay: 200,
      loading: true
    }).then(function (index) {
      loadingMsgIndex = index;
      sendXHR(res.value, showStars)
    });
  });
}

function showStars(stars) {
  botui.message
  .update(loadingMsgIndex, {
    content: stars
  })
  .then(init); // ask again for repo. Keep in loop.
}

init();

但是,当我访问 index.html 文件并输入内容时,答案似乎是空白。我期待得到 Hello World! 值。通过查看flask日志,我也看到GET请求的状态是200。

更新:我使用 brave/safari 浏览器。

我还不知道我哪里错了。任何帮助表示赞赏!谢谢

CORS issue can be solved with Flask-CORS 扩展。
使用 pip 安装它:

$ pip install flask-cors

然后在你的 API:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)