带有Vue.js的axios中的PUT请求问题

时间:2019-07-10 17:51:19

标签: vue.js axios

我正在构建一个智能家居应用程序。我在将PUT请求发送到我的rest api时遇到问题(我用flask构建它),但是当我尝试发送请求时,它给了我HTTP 400错误((未捕获(承诺)错误:请求失败,状态码为400))。你能帮我吗?

import axios from 'axios';
export default {
    data: function() {
        return {
            value: 0,
            lampName: 'Kitchen',
        };
    },
    mounted () {
        axios
        .get("http://127.0.0.1:5000/lamp/" + this.$route.params.id)
        .then(response => (this.value = response.data))
    },
    methods: {
        updateValue () {
            axios
                .put('http://127.0.0.1:5000/lamp/' + this.$route.params.id,
                {value: this.value},
                {headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            })
        }
    }
}

3 个答案:

答案 0 :(得分:0)

这是失败的请求:

axios
    .put('http://127.0.0.1:5000/lamp/' + this.$route.params.id,
    {value: this.value},
    {headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
})

我不知道您的服务器期望什么,但是您在发送JSON数据时将content-type设置为application/x-www-form-urlencoded。看起来这种不匹配可能是导致您出现问题的原因。如果您在浏览器开发人员工具的网络部分中检查了请求,则应该能够看到此消息。

如果您需要使用application/x-www-form-urlencoded,那么我建议您阅读axios文档,因为您不能仅仅传递这样的数据对象:

https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format

简而言之,尽管有一些实用程序可以减轻繁琐的工作,但您仍需要手动构建主体字符串。

如果您实际上想要JSON数据,则只需删除content-type标头。 Axios应该为您设置一个合适的content-type

答案 1 :(得分:0)

<块引用>

将您的方法作为 post 方法传递并定义放入表单数据 formData.append('_method', 'PUT') .

     updateValue () {
            axios
                .post('http://127.0.0.1:5000/lamp/' + this.$route.params.id,
                {value: this.value, _method: 'PUT'},
                {headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            })
        }

答案 2 :(得分:0)

尝试将方法字段添加到表单中并像这样以post方式发送

#include <fstream>
#include <iostream>

void FileExists(std::string myfile){
std::ifstream file(myfile.c_str());

if (file) {
    std::cout << "file exists" << std::endl;
}
else {
    std::cout << "file doesn't exist" << std::endl;
}
}

int main() {
FileExists("myfile.txt");

return 0;
}

然后尝试定期发送数据 我认为它是这样工作的:

formData.append('_method', 'PUT')