Home Web Front-end JS Tutorial Detailed explanation of how to remove # sign from URL in Angular2

Detailed explanation of how to remove # sign from URL in Angular2

Apr 14, 2018 am 11:13 AM
operate Detailed explanation

This time I will bring you a detailed explanation of the operation of removing the # number from the URL in Angular2. What are the precautions for removing the # number from the URL in Angular2. The following is a practical case. Let’s take a look. .

Preface

This article mainly introduces the relevant content about removing the # sign in the URL in Angular2. This is a problem I encountered recently at work. I feel it is necessary to share it with you. I won’t say much below, let’s take a look at the details. Let’s introduce it.

1. Why should it be removed?

  • Angular officially pointed out: If there is not enough reason to use hash style (#), try to use the HTML5 mode routing style;

  • If the hash style is configured, the deep path in WeChat payment or Angular will still be There will be a 404 problem;

  • When you need to use tools such as GA, because you cannot obtain the URL after the # number, a path will be sent to it every time the route is switched;

  • '#'A bit ugly.

2. How to remove it?

There are four methods:

  • Front-end ngx

  • Front-end Apache

  • Front-end Tomcat

  • GithubPages / Code Cloud Pages 404 page

2.1 Front-end

Add

<base href="/" rel="external nofollow" >
Copy after login

to the head of index.html app.module.ts

import { ROUTER_CONFIG } from './app.routes.ts';
@NgModule({
 imports: [
 ...
 RouterModule.forRoot(ROUTER_CONFIG) 
 // RouterModule.forRoot(ROUTER_CONFIG, { useHash: true } ) 这样写是带#的
 ], 
})
Copy after login

app.routes.ts:

import { NgModule } from '@angular/core';
import { Routes } from '@angular/router';
export const ROUTER_CONFIG: Routes = [
 {
 ...
 }
];
Copy after login

What happens if you only configure the front end?

If you only configure the front end, the '#' will be removed, but as soon as the page is refreshed, a 404 will appear, indicating an error in path resolution.
Angular is a single-page application that implements the front-end routing function. The backend can no longer control routing jumps and throw all the business logic originally belonging to the backend to the frontend.

  • When the user refreshes the page (http://gitee.poetry/life), the request is first submitted to the WebServer background. If the background route does not have routing management for the corresponding page, a 404 error will occur.

  • If the user first visits the homepage (http://gitee.poetry) and then jumps to the page (http://gitee.poetry/life), the jump is made by Angular Access to the URL managed by the front desk is normal.

Then we can solve the 404 problem by asking WebServer to forward all routing URLs managed by Angular to index.html, which is the configuration information introduced later.

Thinking: Why is the hash mode not 404?

2.2 ngx configuration

Those with '***' need to configure the nginx.conf file content yourself

server {
 listen 80; #监听的端口号 
 server_name my_server_name; # 服务器名称 ***
 root /projects/angular/myproject/dist; #相对于nginx的位置 ***
 index index.html; #如果index.html存在,就结束查找过程,把这个文件附加到请求的request_uri后面,并且发起一个内部的redirect。
 location / { # / 是匹配所有的uri后执行下面操作
 try_files $uri $uri/ /index.html; #try_files先寻找名为 $uri 文件,没有则寻找 $uri/ 文件,再没有就寻找/index.html
 }
}
Copy after login

try_files detailed explanation:

For example, the request is https://deepthan.gitee.io/poetry/life, $uri is ‘/life’. If neither ‘$uri’ nor $uri/’ is found, it will fall back to the last option of try_files. /index.html initiates an internal "subrequest", which is equivalent to nginx initiating an HTTP Request to https://deepthan.gitee.io/poetry/index.html. This request will be sent by location ~ .php$ { ... } catch, that is, enter the FastCGI handler. The specific URI and parameters are passed to the REQUEST_URI FastCGI and WordPress programs, so are not affected by URI changes.

2.3 Apache

Create a new .htaccess file in the root directory of Apache

RewriteEngine On 
# 如果请求的是现有资源,则按原样执行
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] 
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d 
RewriteRule ^ - [L]
# 如果请求的资源不存在,则使用index.html
RewriteRule ^ /index.html
Copy after login

2.4 Tomcat configuration

Tomcat/conf/web.xml文件上添加
<error-page>
 <error-code>404</error-code>
 <location>/</location>
</error-page>
Copy after login

2.5 GithubPages / Code Cloud Pages 404 Page

For github pages or code cloud pages, we cannot configure Github pages directly, but we can add a 404 page when committing. The simple solution is as follows:

We create a new 404.html in the root directory of the project and completely copy the contents of index.html to 404.html. Doing this github pages will still give a 404 response at the appropriate time, and the browser will handle the page correctly and load our application normally.

About this hack: S(GH)PA: The Single-Page App Hack for GitHub Pages

3. What is the difference in principle between using ‘#’ and without ‘#’?

3.1  这个得先说下什么是前端路由:

以前路由都是后台做的,通过用户请求的url导航到具体的html页面,现在我们在前端可以利用 Angular、vue、react等通过配置文件,达到前端控制路由跳转的功能。

前端路由的实现方法:

  • 通过hash实现 当url的hash发生改变时,触发hashchange注册的回调(低版本没有hashchange事件,通过轮回检测url实现),回调中去进行不同的操作,进行不同的内容展示。
    使用hash来实现的话,URI规则中要带上#,路由中#后边的内容就是hash,我们常说的锚点严格来说应该是页面中的a[name]等元素。

  • HTML5的history api操作浏览器的session history实现
    基于history实现的路由中不带#,就是原始的路由

3.2 Angular中的路由策略

angular2提供的路由策略也是基于上面两个原理实现的,可以在@NgModule中通过providers配置或RouterModule.forRoot()配置:

1) 路由中有#

@NgModule({
 imports:[RouterModule.forRoot(routes,{useHash:true})]
})
Copy after login

@NgModule({
 imports:[RouterModule.forRoot(routes)],
 providers:[
  {provide: LocationStrategy, useClass: HashLocationStrategy} 
 ]
})
Copy after login

HashLocationStragegy

适用于基于锚点标记的路径,比如/#/**,后端只需要配置一个根路由即可。

2) html5路由(无#)

改用 PathLocationStrategy(angular2的默认策略,也就是HTML5路由),使用这个路由的常规路径不带#,这种策略需要后台配置支持,因为我们的应用是单页面应用,如果后台没有正确的配置,当用户在浏览器从一个路由跳往另外一个路由或者刷新时就会返回404,需要在服务端里面覆盖所有的路由情况(后端可以通过nginx或者apache等配置)。

@NgModule({
 imports:[RouterModule.forRoot(routes)],
 providers:[
 {provide: LocationStrategy, useClass: PathLocationStrategy} 
 // 这一行是可选的,因为默认的LocationStrategy是PathLocationStrategy
 ]
})
Copy after login

更改index.html中的base href属性,Angular将通过这个属性来处理路由跳转

<base href="/app/" rel="external nofollow" rel="external nofollow" >
Copy after login

在后端的服务器上,用下面的正则去匹配所有的页面请求导向index.html页面。

we must render the index.html file for any request coming with below pattern
Copy after login

index.html




 
 My App
 <base href="/app/" rel="external nofollow" rel="external nofollow" >
 
 Loading...
 
 
 
Copy after login

3.3 前端路由优缺点

优点:

1.从性能和用户体验的层面来比较的话,后端路由每次访问一个新页面的时候都要向服务器发送请求,然后服务器再响应请求,这个过程肯定会有延迟。而前端路由在访问一个新页面的时候仅仅是变换了一下路径而已,没有了网络延迟,对于用户体验来说会有相当大的提升。

2.在某些场合中,用ajax请求,可以让页面无刷新,页面变了但Url没有变化,用户不能获取到想要的url地址,用前端路由做单页面网页就很好的解决了这个问题。

缺点:

使用浏览器的前进,后退键的时候会重新发送请求,没有合理地利用缓存。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:



The above is the detailed content of Detailed explanation of how to remove # sign from URL in Angular2. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PyCharm usage tutorial: guide you in detail to run the operation PyCharm usage tutorial: guide you in detail to run the operation Feb 26, 2024 pm 05:51 PM

PyCharm is a very popular Python integrated development environment (IDE). It provides a wealth of functions and tools to make Python development more efficient and convenient. This article will introduce you to the basic operation methods of PyCharm and provide specific code examples to help readers quickly get started and become proficient in operating the tool. 1. Download and install PyCharm First, we need to go to the PyCharm official website (https://www.jetbrains.com/pyc

What is sudo and why is it important? What is sudo and why is it important? Feb 21, 2024 pm 07:01 PM

sudo (superuser execution) is a key command in Linux and Unix systems that allows ordinary users to run specific commands with root privileges. The function of sudo is mainly reflected in the following aspects: Providing permission control: sudo achieves strict control over system resources and sensitive operations by authorizing users to temporarily obtain superuser permissions. Ordinary users can only obtain temporary privileges through sudo when needed, and do not need to log in as superuser all the time. Improved security: By using sudo, you can avoid using the root account during routine operations. Using the root account for all operations may lead to unexpected system damage, as any mistaken or careless operation will have full permissions. and

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

What to do if you forget to press F2 for win10 boot password What to do if you forget to press F2 for win10 boot password Feb 28, 2024 am 08:31 AM

Presumably many users have several unused computers at home, and they have completely forgotten the power-on password because they have not been used for a long time, so they would like to know what to do if they forget the password? Then let’s take a look together. What to do if you forget to press F2 for win10 boot password? 1. Press the power button of the computer, and then press F2 when turning on the computer (different computer brands have different buttons to enter the BIOS). 2. In the bios interface, find the security option (the location may be different for different brands of computers). Usually in the settings menu at the top. 3. Then find the SupervisorPassword option and click it. 4. At this time, the user can see his password, and at the same time find the Enabled next to it and switch it to Dis.

Linux Deploy operation steps and precautions Linux Deploy operation steps and precautions Mar 14, 2024 pm 03:03 PM

LinuxDeploy operating steps and precautions LinuxDeploy is a powerful tool that can help users quickly deploy various Linux distributions on Android devices, allowing users to experience a complete Linux system on their mobile devices. This article will introduce the operating steps and precautions of LinuxDeploy in detail, and provide specific code examples to help readers better use this tool. Operation steps: Install LinuxDeploy: First, install

Huawei Mate60 Pro screenshot operation steps sharing Huawei Mate60 Pro screenshot operation steps sharing Mar 23, 2024 am 11:15 AM

With the popularity of smartphones, the screenshot function has become one of the essential skills for daily use of mobile phones. As one of Huawei's flagship mobile phones, Huawei Mate60Pro's screenshot function has naturally attracted much attention from users. Today, we will share the screenshot operation steps of Huawei Mate60Pro mobile phone, so that everyone can take screenshots more conveniently. First of all, Huawei Mate60Pro mobile phone provides a variety of screenshot methods, and you can choose the method that suits you according to your personal habits. The following is a detailed introduction to several commonly used interceptions:

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

See all articles