1

我正在尝试fetch在我的 Vue 2 项目中使用,但是当我尝试file.json在根目录中访问时,它index.html 每次都会加载!我有一种强烈的感觉,这是 Vue 路由器的错。

那么如何防止 Vue 路由器重定向我的 fetches ???

这是我的router.js

import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import Group from "../views/Group.vue";
import Computer from "../views/Computer.vue";
import NoComputer from "../views/NoComputer.vue";
import Error404 from "../views/404.vue";

Vue.use(VueRouter);

const routes = [
{
  path: "/",
  name: "Home",
  component: Home
},
{
  path: "/group/:group",
  component: Group,
  props: true,
  children: [
  { path: '', component: NoComputer },
  {
    path: 'computer/:com',
    component: Computer,
    props: true,
  }
  ]
},
// always at bottom of list
{ path: '*', component: Error404 }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});

export default router;

这是我的收获:

async getComputers() {
    var res = await fetch("/file.json", {
        method: 'GET',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        redirect: 'error',
    });
    console.log(res.json());
},

谢谢你的建议!

4

1 回答 1

0

这不是 Vue 路由器问题。Vue CLI 使用 WebpackdevServerhistoryApiFallback. 这将index.html代替任何404响应返回。该index.html响应意味着您请求的资源 ( file.json) 在指定路径中不存在。

如果file.json是静态资产,请确保它存在于public目录中(即,在它的根目录下/file.json)。

于 2021-03-08T07:33:35.063 回答