POST功能返回空值

时间:2019-07-02 10:45:39

标签: vue.js

Vue.js中的Post Function返回一个空值。

API调用在其他端口上是我的计算机本地的。 GET功能按预期方式工作。 POST功能无法正常工作,仅返回null。

fetch('http://localhost:8080/Exercise/lists/add', {
                method: 'POST',
                headers: {
                    "Content-Type" : "application/json",
                },
                body: JSON.stringify(this.user)
            })
            .then((response) => {
                if(response.ok) {
                    console.log('Response is Ok.');
                }
            })
            .catch((err) => {console.log(err)});
        }

预期添加用户。而是返回一个空值。 Console.log output here..

PostMan "post" service

PostMan "post" service working..

2 个答案:

答案 0 :(得分:0)

根据this site,发布请求的正文的格式类似于'foo = bar&lorem = ipsum'。但在您的情况下,数据是JSON字符串化对象,例如“ {{x“:5,” y“:6}”。这可能会对您的后端有所帮助。

您还可以使用浏览器的网络分隔符控制浏览器和后端之间的请求(对于Firefox,它是Ctrl + Maj + J,然后是“网络”选项卡)。它会告诉您发送到服务器的数据以及响应是什么。

答案 1 :(得分:0)

您应在 Vue 中使用 Axios 进行API调用。您可以从文档https://vuejs.org/v2/cookbook/using-axios-to-consume-apis.html中找到Axios参考。

根据Google中的文档,当您使用POST请求方法时,您需要传递正文,并且上载的图像显示您使用了firstName参数。因此,要么更改您的API并使用正文获取名字,要么您可以执行以下操作:

fetch('http://localhost:8080/Exercise/lists/add?firstName='+JSON.stringify(this.user), {
                method: 'POST',
                headers: {
                    "Content-Type" : "application/json",
                },
                body: ''
            })
            .then((response) => {
                if(response.ok) {
                    console.log('Response is Ok.');
                }
            })
            .catch((err) => {console.log(err)});
        }
相关问题