当前位置:网站首页>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 .
边栏推荐
- 抓包整理外篇fiddler————了解工具栏[一]
- MFC common current path
- Usage differences between isempty and isblank
- isEmpty 和 isBlank 的用法区别
- Severe Tire Damage:世界上第一个在互联网上直播的摇滚乐队
- win11如何添加打印机和扫描仪?win11添加打印机和扫描仪的设置
- [today in history] June 8: the father of the world wide web was born; PHP public release; IPhone 4 comes out
- Le routage des microservices de la passerelle a échoué au chargement des ressources statiques des microservices
- 微信小程序中生成二维码
- 喜新厌旧?IT公司为什么宁愿花20k招人,也不愿涨薪留住老员工
猜你喜欢

Le routage des microservices de la passerelle a échoué au chargement des ressources statiques des microservices

JDBC and MySQL databases
![[today in history] June 23: Turing's birthday; The birth of the founder of the Internet; Reddit goes online](/img/d5/4b3e622ab77bc546ca5d285ef67d8a.jpg)
[today in history] June 23: Turing's birthday; The birth of the founder of the Internet; Reddit goes online
![[today in history] June 3: Microsoft launched Bing search engine; Larry Roberts starts ARPANET; The father of Visual Basic was born](/img/9e/408ae022d9d5d8106e94e71b319d43.png)
[today in history] June 3: Microsoft launched Bing search engine; Larry Roberts starts ARPANET; The father of Visual Basic was born
![[block coding] simulation of image block coding based on MATLAB](/img/d9/a9c45faf40663865893cd58e7e7431.png)
[block coding] simulation of image block coding based on MATLAB

【倒立摆控制】基于UKF无迹卡尔曼滤波的倒立摆控制simulink仿真
![[cloud native] - docker installation and deployment of distributed database oceanbase](/img/02/57ab785acafd8ff0a49c584dd05188.png)
[cloud native] - docker installation and deployment of distributed database oceanbase

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

Win11 cannot create a new text document? Solution to win11 right click failure to create a new text document

Writing based on stm32
随机推荐
[today in history] June 23: Turing's birthday; The birth of the founder of the Internet; Reddit goes online
榜单首发——前装搭载率站上10%大关,数字钥匙方案供应商TOP10
《天天数学》连载53:二月二十一日
[today in history] June 19: iPhone 3GS launched; Pascal was born; Anti terrorist elite begins testing
Unity WebGL打包后怎么运行(火狐配置)
[elevator control system] design of elevator control system based on VHDL language and state machine, using state machine
MFC常用 当前路径
数仓的字符截取三胞胎:substrb、substr、substring
How to enable multi language text suggestions? Win11 method to open multilingual text suggestions
The horizontal scrolling recycleview displays five and a half in one screen, which is lower than the five average distributions
Mysql database foundation: DML data operation language
Online JSON to plaintext tool
【方块编码】基于matlab的图像方块编码仿真
Heartless sword Chinese English bilingual poem 004 Sword
【云原生】-Docker安装部署分布式数据库 OceanBase
[fuzzy neural network] simulation of fuzzy neural network based on MATLAB
[today in history] June 25: the father of notebook was born; Windows 98 release; First commercial use of generic product code
Why are so many people keen on big factories because of the great pressure and competition?
目标检测|SSD原理与实现
Flask Foundation: template inheritance + static file configuration