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 ~

The new front-end lady asked :Vue route history The mode refresh page appears 404 More articles on the question

  1. vue route history The mode refresh page appears 404 problem

    vue hash In mode ,URL in '#', use 'history' Pattern can solve this problem . however history Mode will appear after refreshing the page , Page appears 404. The solution is to use nginx Configure it . stay nginx In the configuration file ...

  2. solve vue route history After mode refresh 404 The problem of

    server { listen ;# The default port is 80, If the port is not occupied, it can be modified server_name localhost; root E:/vue/my_project/dist;#vue Project marking ...

  3. VUE route history Pattern pit --NGINX

    Due to wechat sharing and automatic login , about URL in '#' The address of , It's difficult to deal with ( You need to write some code manually to handle ). There may also be some hidden problems that have not been discovered . If VUE Can be like other (JSP/PHP) The path of the system is the same , There is no such thing ...

  4. vue react route history Mode refresh 404 Problem solution

    vue Single page is required for wechat sharing and automatic login , about URL in ’#’ The address of , It's difficult to deal with . use history Pattern would not have such a problem . But instead history Pattern , There will be a new problem , After the page is refreshed , The page cannot be displayed ...

  5. Vue route history Mode step pit record :nginx Configuration to solve 404 problem

    The problem background : vue-router The default is hash Pattern , Use url Of hash To simulate a complete one url, When url When things change , The page will not be reloaded . But if we don't want to hash This kind of # The path at the end of the number , We can make ...

  6. vue route history Package in mode node Server configuration

    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  his ...

  7. vue Next history After mode refresh 404 Error resolution

    Official documents : https://router.vuejs.org/zh/g... One . Actually measured Linux System Apache To configure : Change the site configuration file , I'm here Directory Added after the label ...

  8. vue route history Pattern ,nginx To configure

    nginx Configure the content # For more information on configuration, see: # * Official English Documentation: http://n ...

  9. Laravel+vue Realization history Pattern URL Feasible plan

    project :laravel + vue Achieve front and rear end separation .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 . h ...

  10. stay nginx Upper Department vue project (history Pattern );

    stay nginx Upper Department vue project (history Pattern ): vue-router The default is hash Pattern , Use url Of hash To simulate a complete one url, When url When things change , The page will not be reloaded . But if we don't want to has ...

Random recommendation

  1. MyBatis Know how much (2)

    MyBatis It absorbs a lot of excellent features and ideas from the most popular relational database access methods , And find out the synergy . The following figure shows MyBatis How does the framework absorb the different ways we have used for database integration for many years What you learned during development ...

  2. QT The hexadecimal integer is automatically supplemented by a string 0 &amp;&amp; Decimal zero complement

    QString str = QString("%1").arg(outChar&0xFF,2,16,QLatin1Char('0')); int a=0001; QStri ...

  3. Lamda Action Func Thread example

    lamda expression Format :( Parameter list  ) => {  The body of the function } effect : Simplify the writing of anonymous methods , It can be used anywhere anonymous methods and strongly typed proxies can be used : Action Is a generic delegate with no return value . Action No reference ...

  4. Sass Use tips

    1. Anything that can be used for css All assignments of property values can be used as sass A variable's value . If the variable value does not match the attribute ,sass It will be treated as an ordinary string . $family: "microsoft yahei", Ari ...

  5. take Maven Of Web Project deployment to windows Of Tomcat in

    So here I'm going to use theta win7 and tomcat8, And tomcat8 Download the compressed package instead of the installation file . First step : First the tomcat8 Installation services ,cmd Change the directory to tomcat8( That is, the folder after decompressing the compressed package ) Of bin Folder , ...

  6. Eclipse newly build Maven web project

    File --> New --> Maven Project --> Choose the storage path --> Choose the skeleton --> Input Maven coordinate --> Preliminary formation , Next, configure 1 ...

  7. Batch close firewall .bat

    Batch close firewall .bat @echo offecho Turn off the firewall with batch processing , Including home and work network locations . Public network location settings .netsh firewall set opmode mode=disable pro ...

  8. Sequential Container

    Notes from C++ Primer Initialize container by iterator When copy a container to another, the contain ...

  9. thorough Spring Boot: How to investigate java.lang.ArrayStoreException

    java.lang.ArrayStoreException analysis This demo To show how to check a spring boot 1 Application upgrade to spring boot 2 What may happen when java.lang.Array ...

  10. Experiment CTF Skynet management system

    You dare to challenge skynet Format :ctf{ } The problem solving link : http://ctf5.shiyanbar.com/10/web1/ When I open the link , Um. , Open and aboveboard release account password , It's not gonna happen , View the source code It seems to be and md ...