我正在尝试将一些数据发布到伪造的API(在本例中为jsonPlaceHolder),其目的是用户可以输入标题和内容,并通过使用axios将其发布到https://jsonplaceholder.typicode.com/posts的此API上,方法是按一个按钮,但我不断收到此问题标题中的错误。
代码如下:
<template>
<div>
<h1>it 2020 people</h1>
<p>type in your title</p>
<input type="text" v-model="title" />
<p>type your content</p>
<textarea cols="30" rows="1" v-model="body"></textarea>
<h3>your title is {{ title }}</h3>
<h3>your content is {{ body }}</h3>
<button v-on:click="post()">post</button>
</div>
</template>
<script>
import Vue from "vue";
import Axios from "axios";
Vue.use(Axios);
export default {
components: {},
data() {
return {
title: "",
body: "",
};
},
methods: {
post: function () {
Vue.axios
.post("https://jsonplaceholder.typicode.com/posts", {
title: this.title,
body: this.body,
userid: 1,
})
.then(function (data) {
return console.log(data);
});
},
},
};
这是在运行任何命令之前出现的错误:
Uncaught (in promise) TypeError: Cannot read property 'protocol' of undefined
at isURLSameOrigin (isURLSameOrigin.js?3934:57)
at dispatchXhrRequest (xhr.js?b50d:115)
at new Promise (<anonymous>)
at xhrAdapter (xhr.js?b50d:13)
at dispatchRequest (dispatchRequest.js?5270:52)
isURLSameOrigin @ isURLSameOrigin.js?3934:57
dispatchXhrRequest @ xhr.js?b50d:115
xhrAdapter @ xhr.js?b50d:13
dispatchRequest @ dispatchRequest.js?5270:52
这是我在按下应该将数据发送到API的按钮后得到的错误:
[Vue warn]: Error in v-on handler: "TypeError: vue__WEBPACK_IMPORTED_MODULE_0__.default.axios is not a function"
found in
---> <App> at src/App.vue
<Root>
warn @ vue.runtime.esm.js?2b0e:619
logError @ vue.runtime.esm.js?2b0e:1884
globalHandleError @ vue.runtime.esm.js?2b0e:1879
handleError @ vue.runtime.esm.js?2b0e:1839
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1862
invoker @ vue.runtime.esm.js?2b0e:2179
original._wrapper @ vue.runtime.esm.js?2b0e:6917
我真的不知道这是什么问题,非常感谢任何有用的信息。 预先感谢。
答案 0 :(得分:0)
axios
不是Vue插件,因此您不能使用axios。相反,您可以创建如下所示的api服务模块:
//apis.js
import axios from 'axios'
const api = axios.create({
baseURL: 'api.domain.com',
headers: {
'Content-Type': 'application/json'
}
})
export default api
,然后在您要发出请求的文件中
import api from './services/api'
export default {
methods: {
async makeRequest() {
try {
const res = await api.get('/endpoint')
console.log(res)
} catch (error) {
console.error(error)
}
}
}
}