简体   繁体   English

Vue 路由器、GitHub 页面和自定义域不适用于路由链接

[英]Vue Router, GitHub Pages, and Custom Domain Not Working With Routed Links

My domain: myname.com我的域名: myname.com
My GitHub repo: myname我的myname回购:我的名字
My GitHub name: myname我的 GitHub 名称: myname

Underlying GH-Pages URL: myname.github.io/myname底层 GH-Pages URL: myname.github.io/myname

My Issue: I have the following pages set up with a History Vue Router: home, contact, projects.我的问题:我使用 History Vue Router 设置了以下页面:主页、联系人、项目。
Whenever I go to myname.com/contact , it routes me to 404 instead.每当我 go 到myname.com/contact时,它会将我路由到 404。 When I click on a link to redirect me to /contacts , it pushes it to the address bar but if you refresh, it routes to 404. I have read posts such as: Deploy Vue to GitHub Pages.当我单击链接将我重定向到/contacts时,它会将其推送到地址栏,但如果您刷新,它会路由到 404。我读过以下帖子: 将 Vue 部署到 GitHub 页面。 Error with vue-router and Vue router on page refresh gets 404 but the issue persists and the custom domain is an added complexity. vue-routerVue 路由器在页面刷新时出错,得到 404 ,但问题仍然存在,并且自定义域增加了复杂性。 I have also read this: Vue Router return 404 when revisit to the url but, there is an example of a React Router page with a Browser Router working on GH-Pages: https://milosrancic.github.io/reactjs-website/activities , repo: https://github.com/milosrancic/reactjs-website . I have also read this: Vue Router return 404 when revisit to the url but, there is an example of a React Router page with a Browser Router working on GH-Pages: https://milosrancic.github.io/reactjs-website/活动,回购: https://github.com/milosrancic/reactjs-website

Here is what I have done:这是我所做的:

  • My package.json has the following line: "homepage": "https://myname.com/"我的package.json有以下行: "homepage": "https://myname.com/"
  • My vue.config.js is exactly this:我的vue.config.js正是这样的:
module.exports = {
    publicPath: '/'
  }
  • My Router is on my path: /src/router/index.js , passed into main.js new Vue() , and is exported like this:我的路由器在我的路径上: /src/router/index.js ,传递到main.js new Vue() ,并像这样导出:
export default new VueRouter({
    base: process.env.BASE_URL,
    mode: 'history',
    routes
})
  • Inside my App.vue (entry component), the template looks like this:在我的App.vue (入口组件)中,模板如下所示:
<template>
  <div id="app">
    <nav-bar></nav-bar>
    <router-view></router-view>
  </div>
</template>

I was unable to fix the problem through Vue but, as tao mentioned, this is likely an issue with GitHub and how they handle URLs.我无法通过 Vue 解决问题,但正如tao所提到的,这可能是 GitHub 以及它们如何处理 URL 的问题。 The simplest fix is to use a Hash Router instead so that the entry URL stays static.最简单的解决方法是使用 Hash 路由器,以便条目 URL 保持 static。 However, this will introduce that, arguably distasteful /#/ in your URL.但是,这将在您的 URL 中引入可以说是令人反感的/#/

Given how catch-all routes are not supported natively, someone has found a workaround for this: https://github.com/rafgraph/spa-github-pages .鉴于原生不支持包罗万象的路线,有人找到了解决方法: https://github.com/rafgraph/spa-github-pages Note: This is likely not good for SEO because the intended URLs do not actually exist.注意:这可能对 SEO 不利,因为预期的 URL 实际上并不存在。 This is doing a trick with their 404 redirects and handling it on the index page.这是他们的 404 重定向并在索引页面上处理它的一个技巧。 This was for a portfolio site and as such, I am ok with this for now.这是一个投资组合网站,因此,我现在可以接受。 If I, or someone else, finds a better solution, this will be updated.如果我或其他人找到更好的解决方案,这将被更新。

Workaround:解决方法:

Inside /public add a file called 404.html and paste the following contents:/public中添加一个名为404.html的文件并粘贴以下内容:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>CHANGE THIS TO YOUR TITLE</title>
    <script type="text/javascript">
      // MIT License
      // https://github.com/rafgraph/spa-github-pages
      // This script takes the current url and converts the path and query
      // string into just a query string, and then redirects the browser
      // to the new url with only a query string and hash fragment,
      // e.g. https://www.foo.tld/one/two?a=b&c=d#qwe, becomes
      // https://www.foo.tld/?/one/two&a=b~and~c=d#qwe
      // Note: this 404.html file must be at least 512 bytes for it to work
      // with Internet Explorer (it is currently > 512 bytes)

      // If you're creating a Project Pages site and NOT using a custom domain,
      // then set pathSegmentsToKeep to 1 (enterprise users may need to set it to > 1).
      // This way the code will only replace the route part of the path, and not
      // the real directory in which the app resides, for example:
      // https://username.github.io/repo-name/one/two?a=b&c=d#qwe becomes
      // https://username.github.io/repo-name/?/one/two&a=b~and~c=d#qwe
      // Otherwise, leave pathSegmentsToKeep as 0.
      var pathSegmentsToKeep = 0;

      var l = window.location;
      l.replace(
        l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +
        l.pathname.split('/').slice(0, 1 + pathSegmentsToKeep).join('/') + '/?/' +
        l.pathname.slice(1).split('/').slice(pathSegmentsToKeep).join('/').replace(/&/g, '~and~') +
        (l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +
        l.hash
      );

    </script>
  </head>
  <body>
  </body>
</html>

Inside /public/index.html , add the following inside the <head> right after <title> :/public/index.html中,在<title>之后的<head>中添加以下内容:

<script type="text/javascript">
// MIT License
// https://github.com/rafgraph/spa-github-pages
// This script checks to see if a redirect is present in the query string,
// converts it back into the correct url and adds it to the
// browser's history using window.history.replaceState(...),
// which won't cause the browser to attempt to load the new url.
// When the single page app is loaded further down in this file,
// the correct url will be waiting in the browser's history for
// the single page app to route accordingly.
(function(l) {
    if (l.search[1] === '/' ) {
    var decoded = l.search.slice(1).split('&').map(function(s) { 
        return s.replace(/~and~/g, '&')
    }).join('?');
    window.history.replaceState(null, null,
        l.pathname.slice(0, -1) + decoded + l.hash
    );
    }
}(window.location))
</script>

This has worked for me and I can now visit the contacts page by simply entering myname.com/contact .这对我有用,我现在只需输入myname.com/contact即可访问联系人页面。 This should also work if you have nested SPA inside /public , using the same trick.如果您在/public中使用相同的技巧嵌套了 SPA,这也应该有效。

I don't totally understand your comment/confusion regarding why/how the re-routing works since you correctly summarized the first half which is Github sees it as an invalid URL and sends it to your custom 404 page.我不完全理解您关于重新路由工作的原因/方式的评论/困惑,因为您正确总结了前半部分,即 Github 将其视为无效的 URL 并将其发送到您的自定义 404 页面。 The 404 page then translates it into a query string pointed at the root page index.html .然后 404 页面将其转换为指向根页面index.html的查询字符串。

Are you missing custom the index.html page in your set up?您是否在设置中缺少自定义index.html页面? index.html itself decodes the query string back into "route param"-type representation so that when your app actually loads, it can initialize with the correct view and state. index.html本身将查询字符串解码回“路由参数”类型的表示,以便当您的应用实际加载时,它可以使用正确的视图和 state 进行初始化。

I actually use this exact setup for my GH pages site: https://mirajp.github.io --> https://www.miraj.dev I actually use this exact setup for my GH pages site: https://mirajp.github.io --> https://www.miraj.dev

If anyone is still looking for answers there is a simpler and neater workaround for this: https://stackoverflow.com/a/65539760/11798104如果有人仍在寻找答案,有一个更简单、更简洁的解决方法: https://stackoverflow.com/a/65539760/11798104

Basically copy index.html and replace it with the name 404.html in the dist folder when you deploy基本上复制index.html并在部署时将其替换为 dist 文件夹中的名称404.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM