首页 > 解决方案 > vue.js 空 POST 到烧瓶服务器

问题描述

我有一个烧瓶服务器,它在“GET /form”上提供以下 jinja 模板

{% extends "base.html" %}

{% block dev_scripts %}
    {{ super() }}
    <script src="https://unpkg.com/lodash@latest/lodash.js"></script>
{% endblock %}

{% block prod_scripts %}
    {{ super() }}
    <script src="https://unpkg.com/lodash@latest/lodash.min.js"></script>
{% endblock %}

{% block contents %}
    <div class="container" id="app">
        {{ errors }}
        <form></form>
    </div>

    <template id="Form-template">
        <form id="myform" class="row border-between" @submit="checkForm" method="post">
            ...
        </form>
    </template>

    <script>
        Vue.options.delimiters = ['[[', ']]'];
        Vue.component('form', {
            name: 'Form',
            template: '#Form-template',
            data() {
                return {
                    data1: {
                        item1: '',
                        item2: '',
                    },
                    data2: {
                        item1: '',
                        item2: '',
                    },
                    method: '',
                    errors: {},
                };
            },
            methods: {
                checkForm(e) {
                    this.errors = {};

                    if (e.submitter.id === 'data1-submit') {
                        this.$data.method = 'data1';

                        if (this.data1.item1 && this.data1.item2) return true;

                        if (!this.data1.item1) {
                            this.errors = _.merge({ data1: { item1: 'item1 required' } }, this.errors);
                        }

                        if (!this.data1.item2) {
                            this.errors = _.merge({ data1: { item2: 'item2 required' } }, this.errors);
                        }
                    }
                    ...

                    e.preventDefault();
                },
            },
        });
        new Vue({
            el: '#app',
        });
    </script>
{% endblock %}

提交表单后,会生成“POST /form”,但 POST 中不包含任何数据。

    if request.method == 'POST':
        print(request.form)
        print(request.json)
        print(request.data)
ImmutableMultiDict([])
None
b''

我尝试使用axios.post(window.location.href, this.$data);,但由于浏览器本身没有发出 POST 请求,因此我无法重定向用户。

有什么方法可以让浏览器发出 POST 请求,如上所述,同时仍然包含来自 vue 组件的数据?

标签: python-3.xvue.jsflask

解决方案


我不习惯 Python / Flask,但您可能缺少内容类型?您还可以在响应返回后重定向到首选 url。

像这样的东西:

const url = window.location.href;
const data = this.$data;
const headers = { "Content-Type": "application/json" }

const response = axios.post(url, data, headers);

if (!response) return false;

window.location.href = enter-preferred-redirect-url-here; 

推荐阅读