The new front-end lady asked: there was a 404 problem refreshing the page in Vue routing history mode

Huawei cloud developer community 2021-09-15 04:13:56
new front-end end lady problem


​​​​ Abstract :vue-router Default hash Pattern —— Use URL Of hash To simulate a complete one URL, So when URL When the change , The page will not be reloaded .

This article is shared from Huawei cloud community 《 Study VueRouter,HTML5 History Pattern , because history The mode refresh page appears 404》, author : DevFeng .

vue-router Default hash Pattern —— Use URL Of hash To simulate a complete one URL, So when URL When the change , The page will not be reloaded .

If you don't want something ugly hash, We can use routing history Pattern , This model takes full advantage history.pushState API To complete URL Jump without reloading the page .

const router = new VueRouter({
mode: 'history',
routes: [...]
})
 Copy code 

When you use history Mode time ,URL Just like normal url, for example yoursite.com/user/id, Good looking, too …

But play it well , Background configuration support is also required . Because our application is a single page client application , If the background is not configured correctly , When the user is directly accessed in the browser oursite.com/user/id It will return 404, It's not good .

So , You want to add a candidate resource to the server that covers all cases : If URL No static resources were matched , The same should be returned index.html page , This page is you app Dependent pages .

# Backend configuration example

Be careful : The following example assumes that you are serving the application in the root directory . If you want to deploy to a subdirectory , You need to use VueCLI Of

publicPath Options (opens new window) And the related router base property (opens new window). You also need to adjust the root directory in the following example to a subdirectory ( For example RewriteBase /name-of-your-subfolder/ Replace RewriteBase/).

#Apache

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
 Copy code 

except mod_rewrite, You can also use FallbackResource (opens new window).

#nginx

location / {
try_files $uri $uri/ /index.html;
}
 Copy code 

# Native Node.js

const http = require('http')
const fs = require('fs')
const httpPort = 80
http.createServer((req, res) => {
fs.readFile('index.html', 'utf-8', (err, content) => {
if (err) {
console.log('We cannot open "index.html" file.')
}
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8'
})
res.end(content)
})
}).listen(httpPort, () => {
console.log('Server listening on: http://localhost:%s', httpPort)
})
 Copy code 

# be based on Node.js Of Express

about Node.js/Express, Please consider using connect-history-api-fallback middleware (opens new window).

#Internet InformationServices (IIS)

1. install IIS UrlRewrite(opens new window)

2. Create a... In the root of your site web.config file , The contents are as follows :

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Handle History Mode and custom 404/500" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
 Copy code 

#Caddy

rewrite {
regexp .*
to {path} /
}
 Copy code 

#Firebase host

In your firebase.json Add :

{
"hosting": {
"public": "dist",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
 Copy code 

# Warning

Give me a warning , Because after that , Your server will not return 404 Error page , Because it returns for all paths

index.html file . To avoid that , You should be Vue The application covers all routing conditions , Then give another example 404 page .

const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})
 Copy code 

perhaps , If you use Node.js The server , You can use the server route to match the incoming URL, Does not return... When there is no match to the route 404, To achieve a fallback .

Click to follow , The first time to learn about Huawei's new cloud technology ~

版权声明
本文为[Huawei cloud developer community]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/09/20210909111329180O.html

  1. 你一定要知道的CSS选择器,web编程开发学习
  2. 作为一名优秀的前端需要了解哪几种设计模式?,前端开发基础学习
  3. 作為一名優秀的前端需要了解哪幾種設計模式?,前端開發基礎學習
  4. Quels modèles de conception faut - il connaître pour être un bon front end?Apprentissage de base du développement de première ligne
  5. Ce que vous devez savoir sur css Selector, Web Programming Development Learning
  6. HTTPS | SSL note - SSL two-way authentication failure (server certificate trust library does not contain client certificate) handshake process (including Wireshark analysis)
  7. HTTPS | SSL notes - SSL two-way authentication failure (client certificate trust library does not contain server certificate) handshake process (including Wireshark analysis)
  8. HTTPS | SSL notes - successful handshake process of SSL two-way authentication (including Wireshark analysis)
  9. [Java Core interview Dictionary] quelles sont les questions d'entrevue courantes pour les demandes de jour 18, get et post?
  10. 【 Java Core interview dictionary】 day 19, what will be interview questions for http protocol?
  11. 使用Docker、Nginx和Jenkins实现前端自动化部署,前端开发技术调研
  12. 使用Docker、Nginx和Jenkins實現前端自動化部署,前端開發技術調研
  13. Utilisation de docker, nginx et Jenkins pour réaliser le déploiement automatique de première ligne et la recherche sur la technologie de développement de première ligne
  14. Que se passe - t - il si le tableau dépasse la limite
  15. Understanding of functions in typescript? What is the difference with JavaScript functions?
  16. EasyUI DataGrid front end sorting by number (custom sorting)
  17. Top2 2021 expérience d'inscription à l'Université Internet, flux de documents standard CSS et flux de documents hors ligne
  18. Yahoo 35 military regulations, how many do you know?
  19. From the experience of a business project landing on vite, I re understood the pre build of vite
  20. Complete process of login business in several ways [good gifts around Nuggets at the end of the text]
  21. Monthly salary 10K yard farmer, job hopping to 40K architect, summary of technical learning Roadmap
  22. Manually compile and deploy LNMP environment (centos7.5 + nginx-1.18.0 + mysql-5.7.30 + php-7.4.14)
  23. The drama "light" of the Republic of China premiered, with a dismal audience rating of less than 0.4, creating the worst audience rating of Hunan Satellite TV!
  24. It is said that Ericsson will cancel Nanjing R & D center
  25. Question d'entrevue commune de Spring Cloud, où est l'avenir de 2021 Java?
  26. Sharedpreferences Replacement - mmkv Integration and Principles, 27 years old Preschool Development
  27. Différence entre TCP et UDP, développement frontal mobile
  28. The whole process of mybatis dynamic proxy implementation of spring series? The correct answer rate is less than 1%
  29. Ajax Foundation
  30. Développement Android comprendre ces entrevues naturelles sans peur, Android Knowledge System
  31. L'expérience de l'entrevue d'embauche de l'école Java peut vous aider à obtenir une entrevue.
  32. Leetcode pinceau question 989 - simple - addition d'entiers sous forme de tableau
  33. Children of the Qiao family: after reading Qiao Zuwang's last selflessness, we can recognize his simple father's love
  34. Partager une petite expérience d'entrevue et obtenir un produit
  35. Solution de capture de paquets https sur la plate - forme Android et analyse des problèmes, Android développe un apprentissage complet
  36. Young people are the first choice for transportation. These hatchbacks suck countless powder. Is it your dish?
  37. "Net red granny" over 70 has countless circle powder by wearing, and is more fashionable than young people
  38. Méthodes de fonctionnement des tableaux couramment utilisées en javascript
  39. Summary of Vue knowledge points
  40. 10 septembre: deuxième visite d'une journée à Yantai, Shandong - vue nocturne de Chaoyang Street, Zhifu District
  41. Front and back end data interaction (V) -- what is Axios?
  42. Windows configures nginx to boot automatically
  43. Des questions d'entrevue communes à Tomcat pour discuter de votre compréhension de la technologie de verrouillage distribué,
  44. JS handscrap, Classic interview question, web front end Development Process
  45. Android 400 questions d'entrevue pour vous aider à entrer dans l'usine, un tour pour vous apprendre à comprendre netty
  46. Développement et projet d'application Web statique côté PC
  47. Recommandé pour le tutoriel Spring Framework, 2021 dernière question d'entrevue d'embauche de la société aiqiyi Java,
  48. La dernière revue scientifique de l'académicien Luo Liqun: architecture de la boucle neuronale pour stimuler la nouvelle Ia
  49. [partage d'expérience de travail], 2021 les dernières questions d'entrevue Java de Baidu, Headlines, etc.
  50. Lisez l'analyse de 497 questions pour l'entrevue d'ingénieur principal Android et vérifiez les lacunes.
  51. Grâce à cette collection de questions d'entrevue d'automne, le salaire de saut d'emploi et l'entrevue de développement audio et vidéo ont doublé.
  52. Prenez d'un coup l'offre de Tencent meituan et jetez un coup d'oeil à cette copie de l'entrevue de printemps!
  53. L'expérience et l'expérience d'un Maverick Java en matière d'entrevue sur les MTD, l'expérience de l'entrevue d'embauche du printemps Java en 2021,
  54. Vue中自定义列表复选框和全选框-案例
  55. Vue bidirectional binding (V-model bidirectional binding,. Sync bidirectional binding,. Sync transfer object)
  56. CSS text overflow ellipsis summary, as you wish
  57. C'est la mode la plus étrange que j'ai jamais vue.
  58. Cases à cocher et toutes les cases à cocher de la liste personnalisée en vue - CAS
  59. Front end interview daily 3 + 1 - day 877
  60. Vue bidirectional binding (V-model bidirectional binding,. Sync bidirectional binding,. Sync transfer object)