首页 > 解决方案 > 从 Vue.js 向烧瓶发送 POST 请求

问题描述

我想从 Vue 组件向 Flask 后端发送一个 POST 请求。我尝试了以下代码:

在 script.js 中:

finishGame: function () {
      this.gameStarted = false;
      this.$http.post("http://127.0.0.1:5000/", "hello")
          .then(function () {
            alert("POST")
          });
    },

在 app.py 中:

from flask import Flask, render_template
from flask_cors import CORS
from model.words import Words

# Set up custom delimiters to avoid Vue.js conflict.
class CustomFlask(Flask):
  jinja_options = Flask.jinja_options.copy()
  jinja_options.update(dict(
    block_start_string='(%',
    block_end_string='%)',
    variable_start_string='((',
    variable_end_string='))',
    comment_start_string='(#',
    comment_end_string='#)',
  ))

app = CustomFlask(__name__)
CORS(app)

word_gen = Words("model/word_lists/onegin.csv")


@app.route('/',  methods=['POST'])
def save_game_results():
    print("Game res!")
    return render_template('index.html', words=word_gen.get_random(500), words_num=word_gen.size())


@app.route('/')
def play_hat():
    return render_template('index.html', words=word_gen.get_random(500), words_num=word_gen.size())

该脚本包含更多代码,但该finishGame函数肯定会运行,并且只有盯着的部分this.$http被忽略。该代码不会产生任何错误,但save_game_results()在被调用时永远不会finishGame()被调用。

我已经尝试过:

  1. 替换"http://127.0.0.1:5000/""/".
  2. "http://127.0.0.1:5000/""http://127.0.0.1:5000/go"和替换@app.route('/', methods=['POST']) _@app.route('/go', methods=['POST'])

它没有奏效。

标签: javascriptvue.jsflaskvue-component

解决方案


推荐阅读