Home Web Front-end JS Tutorial How to remove the # sign from the url in Angular2 (detailed tutorial)

How to remove the # sign from the url in Angular2 (detailed tutorial)

Jun 19, 2018 pm 03:52 PM
angular angularjs url parameter

This article mainly introduces you to the relevant information on how to remove the # sign in the URL in Angular 2. The article first introduces and analyzes the reasons and methods of removing the # sign in detail, and then demonstrates the removal through sample code. Friends who need it can refer to it

Preface

This article mainly introduces the relevant content about removing the # sign from the URL in Angular2 , this is a problem I encountered at work recently, and I feel it is necessary to share it with everyone. I won’t go into more words below, let’s take a look at the detailed introduction.

1. Why should it be removed?

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

  • If the hash style is configured, 404 problems will still occur in WeChat payment or Angular's deep path;

  • When you need to use tools such as GA, due to the inability to Obtaining the URL after the # sign will cause a path to be sent to it every time the route is switched;

  • '#' is 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

app.module.ts

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

app.routes.ts to the head of

#index.html:

import { NgModule } from &#39;@angular/core&#39;;
import { Routes } from &#39;@angular/router&#39;;
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, 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, 404 will appear. mistake.

  • If the user first visits the homepage (http://gitee.poetry) and then jumps to the page (http://gitee.poetry/life), then this jump It is a URL managed by the Angular frontend, and access is normal.

Then we can solve the 404 problem by letting WebServer 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

With '***', you 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:

If the request is https://deepthan.gitee.io/poetry/life, $uri is '/life'. If '$uri''$uri/' cannot be found, it will fall back. Go to the last option of try_files/index.html to initiate an internal "sub-request", which is equivalent to nginx initiating an HTTP request to https://deepthan.gitee.io/poetry/index.html. This request will be blocked by location ~ .php$ { ... } catch, that is, it will enter the FastCGI handler. The specific URI and parameters are passed to FastCGI and WordPress programs in REQUEST_URI, so they are not affected by URI changes.

2.3 Apache

Create a .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 directly configure Github pages, 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. With '#' and without '# 'What's the difference in principle?

3.1 Let’s first talk about what front-end routing is:

In the past, routing was done in the background, and the user navigated to the URL requested by the user. For specific HTML pages, now we can use Angular, vue, react, etc. on the front end to achieve the front-end control route jump function through configuration files.

Implementation method of front-end routing:

  • Implemented through hash When the hash of the URL changes, the callback of hashchange registration is triggered (lower versions do not have hashchange events, and are detected through reincarnation url implementation), perform different operations and display different content in the callback.

    If hash is used to implement it, # must be included in the URI rules. The content after # in the route is the hash. Strictly speaking, the anchor point we often refer to should be the a[name] and other elements in the page.

  • HTML5’s history api operates the browser’s session history implementation

    Routes implemented based on history without # are the original routes

3.2 Routing strategy in 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地址,用前端路由做单页面网页就很好的解决了这个问题。

缺点:

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

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

使用JavaScript如何实现抽奖系统

详细解答vue的变化对组件有什么影响?

使用Parcel如何打包

The above is the detailed content of How to remove the # sign from the url in Angular2 (detailed tutorial). 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)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1225
24
Why NameResolutionError(self.host, self, e) from e and how to solve it Why NameResolutionError(self.host, self, e) from e and how to solve it Mar 01, 2024 pm 01:20 PM

The reason for the error is NameResolutionError(self.host,self,e)frome, which is an exception type in the urllib3 library. The reason for this error is that DNS resolution failed, that is, the host name or IP address attempted to be resolved cannot be found. This may be caused by the entered URL address being incorrect or the DNS server being temporarily unavailable. How to solve this error There may be several ways to solve this error: Check whether the entered URL address is correct and make sure it is accessible Make sure the DNS server is available, you can try using the "ping" command on the command line to test whether the DNS server is available Try accessing the website using the IP address instead of the hostname if behind a proxy

PHP function introduction—get_headers(): Get the response header information of the URL PHP function introduction—get_headers(): Get the response header information of the URL Jul 25, 2023 am 09:05 AM

PHP function introduction—get_headers(): Overview of obtaining the response header information of the URL: In PHP development, we often need to obtain the response header information of the web page or remote resource. The PHP function get_headers() can easily obtain the response header information of the target URL and return it in the form of an array. This article will introduce the usage of get_headers() function and provide some related code examples. Usage of get_headers() function: get_header

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

What is the difference between html and url What is the difference between html and url Mar 06, 2024 pm 03:06 PM

Differences: 1. Different definitions, url is a uniform resource locator, and html is a hypertext markup language; 2. There can be many urls in an html, but only one html page can exist in a url; 3. html refers to is a web page, and url refers to the website address.

New feature in PHP version 5.4: How to use callable type hint parameters to accept callable functions or methods New feature in PHP version 5.4: How to use callable type hint parameters to accept callable functions or methods Jul 29, 2023 pm 09:19 PM

New feature of PHP5.4 version: How to use callable type hint parameters to accept callable functions or methods Introduction: PHP5.4 version introduces a very convenient new feature - you can use callable type hint parameters to accept callable functions or methods . This new feature allows functions and methods to directly specify the corresponding callable parameters without additional checks and conversions. In this article, we will introduce the use of callable type hints and provide some code examples,

What do product parameters mean? What do product parameters mean? Jul 05, 2023 am 11:13 AM

Product parameters refer to the meaning of product attributes. For example, clothing parameters include brand, material, model, size, style, fabric, applicable group, color, etc.; food parameters include brand, weight, material, health license number, applicable group, color, etc.; home appliance parameters include brand, size, color , place of origin, applicable voltage, signal, interface and power, etc.

C++ function parameter type safety check C++ function parameter type safety check Apr 19, 2024 pm 12:00 PM

C++ parameter type safety checking ensures that functions only accept values ​​of expected types through compile-time checks, run-time checks, and static assertions, preventing unexpected behavior and program crashes: Compile-time type checking: The compiler checks type compatibility. Runtime type checking: Use dynamic_cast to check type compatibility, and throw an exception if there is no match. Static assertion: Assert type conditions at compile time.

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

See all articles