未捕获(在承诺中)TypeError:无法将未定义或空转换为对象
2021-11-09
5638
我对 Vue 还很陌生,我一直在尝试弄清楚如何使用 axios 调用 Java API。
vue.config.js
module.exports = {
devServer: {
proxy: 'https://localhost:8080'
}
}
main.js
import { createApp } from 'vue'
import axios from "axios"
import VueAxios from 'vue-axios'
import App from './App.vue'
import store from "./store"
import router from "./router"
import './index.css'
const app = createApp(App)
app.use(VueAxios, axios)
app.use(router)
app.use(store)
app.mount('#app')
Dashboard.vue
<template>
{{responsedata}}
</template>
<script>
export default {
name: 'Dashboard',
data() {
return {
responsedata: {}
}
},
async mounted() {
const { data } = await this.axios.get('/home')
console.log(data)
}
}
</script>
但是,无论我如何尝试,它总是给出错误:
Uncaught (in promise) TypeError: Cannot convert undefined or null to object
at Function.keys (<anonymous>)
at mergeConfig (axios.js:1308)
at Axios.request (axios.js:1431)
at Axios.<computed> [as get] (axios.js:1521)
at Function.wrap [as get] (axios.js:7)
at Proxy.mounted (Dashboard.vue:19)
at callWithErrorHandling (runtime-dom.esm-bundler-6174b24b.js:8129)
at callWithAsyncErrorHandling (runtime-dom.esm-bundler-6174b24b.js:8138)
at Array.hook.__weh.hook.__weh (runtime-dom.esm-bundler-6174b24b.js:3392)
at flushPostFlushCbs (runtime-dom.esm-bundler-6174b24b.js:8330)
在这个错误中,我编辑了 Dashboard.vue:19 的路径,但它来自那里。
此行给出错误:
const { data } = await this.axios.get('/home')
。
API 后端如下所示:
@WebServlet
@Path("/home")
public class HomeResource {
private IServerService serverService;
@Inject
public void setServerService(IServerService serverService) {
this.serverService = serverService;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getServers(@Context HttpServletRequest req) {
System.out.println("hello");
HttpSession session = req.getSession();
session.setMaxInactiveInterval(Time.HALF_AN_HOUR.time);
return Response
.ok()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Credentials", "true")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", Time.HALF_AN_HOUR.time)
.entity(serverService.getServers())
.build();
}
}
API 在本地主机端口 8080 上运行,Vue 应用程序在本地主机端口 3000 上运行。我不确定我是否错误地执行了跨域操作或做了完全不同的事情。我所做的只是尝试从 API 获取数据并将其显示到前端。
附言:感谢您的帮助。
3个回答
试试这个:
methods: {
getData() {
this.axios.get('/home')
.then(response => {
console.log(response.data)
})
.catch(err => {
console.log(err, err.response)
})
}
},
mounted() {
this.getData()
}
另外,我认为您需要在
main.js
文件中将 axios baseUrl 传递给 vue-axios 之前设置它。像这样:
axios.defaults.baseURL = 'https://localhost:8080'
app.use(VueAxios, axios)
mahdikmg
2021-11-12
如果您的服务器位于不同的 URL 和/或端口上,则需要为 Axios 提供完整的 URL,例如
localhost:8080/home
。目前,Axios 正在尝试获取
localhost:3000/home
,它位于 Vue 端,而不是 API 端。
Dan P
2021-11-09
你试过了吗?
async created() {
const { data } = await this.axios.get('http://localhost:8080/home')
console.log({ data })
}
user3067684
2021-11-12