Lỗi reload trang khi triển khai Angular hoặc React trên IIS
Bối cảnh
Lý do / Vấn đề
Giải pháp
Có 2 cách xử lý vấn đề này:
Cách 1 là enable chế độ Hash tức là URL luc này thêm # ở đuôi domain sau đó đến routing. Cách này ok nhưng URL không tự nhiên lắm. Chúng ta chỉ cần sử dụng useHash là true ở phần config NgModule là được.
@NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(routes, { useHash: true })
],
bootstrap: [AppComponent]
})
export class AppModule { }
Cách 2 thì config ở file web.config trong web App, chúng ta cần tạo file web.config trong thư mục root của app và nội dung như sau:
<?xml version="1.0"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="React Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
Nhớ là cần cài URL Rewrite Module cho IIS nhé.