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 05:07:50
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 Vue Router,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: [...]
})

When you use history Mode time ,URL Just like normal url, for example  http://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  http://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 Vue CLI 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>

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

#nginx

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

# 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)
})

# be based on Node.js Of Express

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

#Internet Information Services (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>

#Caddy

rewrite {
regexp .*
to {path} /
}

#Firebase host

In your firebase.json Add :

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

# 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 }
]
})

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/20210909115108160a.html

  1. The new front-end lady asked: there was a 404 problem refreshing the page in Vue routing history mode
  2. A Simple Css Meun
  3. Vue modifier dynamiquement le style de l'élément externe du composant
  4. Vue V - si problème non valable
  5. N'osez pas vous opposer à l'intervieweur et obtenir des commentaires personnels des stagiaires d'offer Ali après cinq rondes d'entrevue.
  6. Améliorer continuellement leur capacité à créer des primes, et les questions d'entrevue Java d'Alibaba Huawei Tencent et d'autres grandes usines sont sautées en octets.
  7. The new front-end lady asked: there was a 404 problem refreshing the page in Vue routing history mode
  8. vue v-if未生效問題
  9. Je ne comprends pas comment la machine virtuelle JVM peut encore interviewer, et j'ai terminé ce dictionnaire d'entrevue Java de 1307 pages.
  10. Dongxh, mid autumn festival gifts 🥮, [CSS starry sky realization, Mid Autumn Festival poem]
  11. What if you want to see the moon and don't want to go out
  12. Mid Autumn Festival, Chang'e looks at the moon
  13. Mid Autumn Festival special! Use the simplest animation animation to make the most local and trendy holiday blessing greeting card. This romantic male and female tears of Xiao Chen.
  14. [Pixi] super beautiful! How to make mid autumn festival scene level animation!!
  15. Echarts realizes the rotation of the moon (super simple, you can see it at a glance)
  16. Dart mixin full resolution
  17. Some suggestions on Vue code readability | comments are rewarded
  18. 120 lines of code to achieve pure web video editing
  19. Yang yangsun took a selfie to celebrate his 30th birthday, and Wang Yanlin sent blessings.
  20. Comment passer une entrevue avec une entreprise Internet de première ligne, Android Classic Getting started tutoriel
  21. Comment essayer un développeur Android vraiment niveau, 【 résumé de l'entrevue 】
  22. Wang Ou went back to the hotel with the man at night. It was suspected that his relationship was open. The netizen replied mercilessly: is the man single
  23. 借助HTML ping属性实现数据上报
  24. APNG在线制作、兼容、播放和暂停
  25. Apng production, compatibilité, lecture et pause en ligne
  26. Mise en œuvre de l'escalade des données avec l'attribut de Ping HTML
  27. Comment envoyer 100 000 requêtes http le plus rapidement possible
  28. JQuery Basics
  29. Front and back end data interaction (V) -- what is Axios?
  30. Serverless is a model architecture invented driven by economic benefits- Grady
  31. Les questions d'entrevue pour les ingénieurs Java d'Internet, les intervieweurs rencontrés sont tous de niveau architecte,
  32. Cinq ans d'entrevue d'expérience en développement Java, découvrez les questions que vous devez poser lors de l'entrevue d'embauche du printemps Java de cette année.
  33. La dernière collection de questions d'entrevue Java haute fréquence organisée cette année, 2021 Java Universal Popular Framework
  34. Intel selected Weilai es8 to promote driverless taxis in Europe
  35. JavaScript operator (1), Web Development Engineer
  36. Trier les questions d'entrevue Javascript, trier les points de connaissance des itinéraires d'apprentissage
  37. Song Mengjun's "sleepless night" triggered an upsurge of dance storm after 00
  38. Module management of "free and open source" front-end spa project crudapi background management system based on Vue and Quasar (14)
  39. Encapsulated PHP sends HTTP requests with curl. Get and post are very easy to use
  40. Front and back end data interaction (V) -- what is Axios?
  41. Flutter: résoudre le futur blocage en utilisant Isolate
  42. Résumé des opérations courantes pour les données de structure de l'arbre frontal
  43. Ant Design Transfer Twin Tree Shuttle box "make Wheels"
  44. De la carte de pensée à la base et à l'approfondissement, prenez note de l'expérience d'entrevue d'un octet sautant le poste de recherche et développement Java.
  45. Apprenez les composants d'implémentation de vue et Publiez - les à NPM
  46. [Questions d'entrevue à haute fréquence] À vous de choisir
  47. Une faible connaissance de beginpath () provoque une superposition de style lors de la peinture d'un dessin en toile
  48. React Hooks, laisse - moi t'emmener étudier.
  49. Comment la copie profonde résout - elle les références circulaires?
  50. JavaScript Advanced Programming (3rd Edition) Reading note 6
  51. Analyse de l'URL
  52. Discussion préliminaire sur xss
  53. Solution: développement de la page Web Wechat, obtenir la fosse Piétinée par le flux d'entrée de la caméra via navigator.mediadevice.getusermedia ()
  54. Des milliers de questions d'entrevue sélectionnées n'ont pas encore ét é effacées.
  55. Les questions d'entrevue de niveau intermédiaire et avancé d'Android au fil des ans sont entièrement incluses, et l'algorithme est distribué microservice
  56. J'ai résumé toutes les questions d'entrevue.
  57. Compréhension de la réactivité des données de vue
  58. Note de service CSS (vi): Flex, page mobile et mise en page réactive
  59. JavaScript Review sketch - 1
  60. Analyse du bootstrap webpack