gpt4 book ai didi

javascript - 未捕获( promise )TypeError : Cannot read property 'protocol' of undefined

转载 作者:行者123 更新时间:2023-12-05 02:48:56 24 4
gpt4 key购买 nike

我正在尝试将一些数据发布到一个伪造的 API,在本例中是 jsonPlaceHolder,我的想法是用户可以输入标题和内容并将其发布到此 API https://jsonplaceholder.typicode.com/posts通过按下按钮使用 axios,但我一直在这个问题的标题中收到错误。

代码如下:

<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

我真的不知道问题出在哪里,非常感谢任何有用的信息。提前致谢。

最佳答案

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)
}
}
}
}

关于javascript - 未捕获( promise )TypeError : Cannot read property 'protocol' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64235943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com