【问题标题】:Vue Router interfering with Javascript fetchVue 路由器干扰 Javascript 获取
【发布时间】:2021-03-08 15:33:35
【问题描述】:

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

那么我怎样才能防止 Vue 路由器重定向我的获取呢???

这是我的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());
},

感谢您的建议!

【问题讨论】:

    标签: vue.js fetch vue-router


    【解决方案1】:

    这不是 Vue 路由器问题。 Vue CLI 使用 Webpack 的 devServer,它启用了 historyApiFallback。这将返回 index.html 代替任何 404 响应。 index.html 响应表示您请求的资源 (file.json) 在指定路径中不存在。

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

    【讨论】:

      猜你喜欢
      • 2015-10-12
      • 2021-05-05
      • 1970-01-01
      • 2015-05-09
      • 1970-01-01
      • 2021-10-28
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多