当前位置:网站首页>Single page application (SPA) hash route and historical API route
Single page application (SPA) hash route and historical API route
2022-06-28 02:59:00 【allway2】
We can base on the Web Accessed in the application URL To determine what page the user sees . Use modern single page applications ( SPA ) There is more than one way to manage routes . In this paper , We will study Hash route How it works . We also explained the use of history API and Browser router More modern routing methods . These examples will use React Router library .
Hash router
# As URL A part of has existed for a long time . It is located in the... That points to a specific resource in the web page URL Before the optional segment of . Take a look at this example :
https://developer.mozilla.org/en-US/docs/Web/API/URL#properties |
When we visit the above page , The browser will traverse DOM The tree comes to look for attribute id The elements of .
<h2 id="properties"> <ahref="#properties"title="Permalink to Properties">Properties</a> </h2> |
Because the browser can find the above elements , It scrolls down the view .
URL There is another important feature of the well number in . Let's look at developer tools :

above , We can see that the browser does not send to the server #properties value . It is interpreted by the browser and passed through JavaScript visit .
console.log(window.location.hash); // #properties |
These facts make hashes a good candidate to use when creating routes for single page applications . Use SPA, We usually provide the same initial for each page HTML Code . And then we use JavaScript according to URL Generate page .
We can easily experience the above . Let's take a look at server pair usage Create React App The response of the created application :

We can see that the server is responding < div id = "root" / > And a set of JavaScript file . We want each route of the application to get the above response . therefore , Our server will not receive information about the exact path the user wants to access , This is very convenient .
Use a hash router
To be in React Using hash router in , We can use React Router library .
npm install react-router-dom |
import React from'react'; import{ HashRouter,Route}from'react-router-dom'; import Posts from'./Pages/Posts'; import LandingPage from'./Pages/LandingPage'; export constApp=()=>( <HashRouter> <Route exact path='/' component={ LandingPage} /> <Route exact path='/posts' component={ Posts} /> </HashRouter> ) |
Doing so creates two routes for us :
- https : //app.com/#/
- https : //app.com/#/posts
In the underlying ,React Router Used history library . Upcoming v6.0.0 Will use older browsers that are no longer supported History Library version of . This is because Used History API. This means that we will be using Internet Explorer 9 And earlier versions . If for some reason , Your target is a very old browser , You should use the old version of React Router.
benefits
The main selling point of hash routing is that the browser will not send information about the route to Web The server . Thanks to that , The configuration is very simple .
shortcoming
The problem with hash routing is that it doesn't seem appropriate . This is because users are usually used to clean and simple URL. therefore , The middle hash may look strange .
Besides , Use a hash router May be considered right SEO adverse .
Browser router
An alternative to the above solution is the browser router . It is considering the use of History API In the case of . Use History API, We can use it directly JavaScript Operating browser history .
For a long time , We have been able to use JavaScript change URL.
document.location.href='https://developer.mozilla.org/'; |
Although the above method is effective , But it also reloads the page . therefore , It makes it less suitable for single page applications .
We can change window . Location .hash Property has no page reload , But this only changes the hash value .
Use History API, We can change the current... Without triggering a page reload URL.
window.history.pushState({ },null,'https://developer.mozilla.org/') |
The first parameter is the state we want to associate with the new item . It can be any serializable data . For more information , Please check out MDN file .
Although the above functions are very powerful , But it also has some limitations . Provided URL Must match the From the same source .
If you want to know about History API For more information , Please check out This page .
Use React Router In the library BrowserRouter It looks very simple :
import React from'react'; import{ BrowserRouter,Route}from'react-router-dom'; import Posts from'./Pages/Posts'; import LandingPage from'./Pages/LandingPage'; export constApp=()=>( <BrowserRouter> <Route exact path='/' component={ LandingPage} /> <Route exact path='/posts' component={ Posts} /> </BrowserRouter> ) |
The above code creates two routes for us :
- https : //app.com/
- https : //app.com/posts
We can notice these URL No longer contains hash characters . This means that even if we develop single page applications , The browser will also change the entire URL Send to server . Even if we have used React Router Defines a route , We use to host our application Web The server may not know it .
visit https : //app.com/posts Routing can lead to 404 Not Found error . We need to configure our Web The server responds to our React Applications , Whatever the exact path it takes to work . By doing so , We let React Router Complete all necessary work , Based on URL Determine what to render .
Web The server configuration will vary , It depends on what you are using nginx、Apache、Amazon S3 Or something else .
benefits
BrowserRouter A big advantage of URL It looks clearer . They no longer contain # character , This is right SEO It may also be a good thing . Use BrowserRouter, Our users will no longer view URL Notice immediately that they are working on a single page application .
shortcoming
although BrowserRouter There are many advantages , But it requires additional configuration costs . Each one URL Point to our React Applications can be cumbersome . therefore , We need to Web The server is configured to always use the same HTML Respond to every possible URL. If we want to be homologous API Provide services , We need to create a pattern for it , And if the URL contain * / api / * Pattern , Not for React Applications provide services .
Generalization
In this paper , We introduced HashRouter and BrowserRouter The main characteristics of . While doing so , We also describe some of the mechanisms that work under their hood . The fact proved that , They have their own advantages and disadvantages . Official React Router file Encourage us to use BrowserRouter, Even if it needs to be in Web Additional configuration on the server side .
边栏推荐
- 第三批入围企业公示!年度TOP100智能网联供应商评选
- 新手炒股开户选哪家证券平台办理是最好最安全的
- 目标检测|SSD原理与实现
- 【模糊神经网络】基于matlab的模糊神经网络仿真
- be fond of the new and tired of the old? Why do it companies prefer to spend 20K on recruiting rather than raise salaries to retain old employees
- SQL报了一个不常见的错误,让新来的实习生懵了
- ADB double click the power key command
- Intel Ruixuan A380 graphics card will be launched in China
- Step by step interpretation of crf+bilstm code
- Exploration on the construction path of real-time digital warehouse integrating digital intelligence learning and streaming batch
猜你喜欢

Win11如何关闭最近打开项目?Win11关闭最近打开项目的方法

如何判断线程池已经执行完所有任务了?

Exploration on the construction path of real-time digital warehouse integrating digital intelligence learning and streaming batch

CMU提出NLP新范式—重构预训练,高考英语交出134高分
![[2D code image correction and enhancement] simulation of 2D code image correction and enhancement processing based on MATLAB](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
[2D code image correction and enhancement] simulation of 2D code image correction and enhancement processing based on MATLAB

在线文本按行批量反转工具

How to run unity webgl after packaging (Firefox configuration)

How to judge that the thread pool has completed all tasks?

CMU puts forward a new NLP paradigm - reconstructing pre training, and achieving 134 high scores in college entrance examination English

【活动早知道】LiveVideoStack近期活动一览
随机推荐
Stm32f1 and stm32subeide programming example - metal touch sensor driver
【云原生】-Docker安装部署分布式数据库 OceanBase
Get 5 offers after being notified of layoffs
[today in history] June 2: Apple launched swift programming language; China Telecom acquires China Unicom C network; OS X Yosemite release
[today in history] June 6: World IPv6 launch anniversary; Tetris release; Little red book established
[today in history] June 8: the father of the world wide web was born; PHP public release; IPhone 4 comes out
SQL reported an unusual error, which confused the new interns
How to enable multi language text suggestions? Win11 method to open multilingual text suggestions
A low-cost method to increase private domain traffic with simple maintenance
ADB double click the power key command
如何开启多语言文本建议?Win11打开多语言文本建议的方法
[block coding] simulation of image block coding based on MATLAB
[today in history] June 23: Turing's birthday; The birth of the founder of the Internet; Reddit goes online
Writing based on stm32
[fuzzy neural network] simulation of fuzzy neural network based on MATLAB
STM32F1与STM32CubeIDE编程实例-金属触摸传感器驱动
[today in history] June 1: Napster was founded; MS-DOS original author was born; Google sells Google SketchUp
转载文章:数字经济催生强劲算力需求 英特尔发布多项创新技术挖掘算力潜能
[today in history] June 15: the first mobile phone virus; AI master simahe was born; Chromebook launch
《天天数学》连载53:二月二十一日