ASP에서 VueJS에 의한 경로 처리 방법.엔드포인트를 사용하는 NET Core?
ASP로 VueJS SPA를 만들려고 한다.백엔드의 NET 코어
이후dotnet SDK
버전3.0.100
Vue를 더 이상 지원하지 않고, React 앱을 만들었다.
dotnet new react
그리고 교환했다.ClientApp
Vue 앱으로
rm -rf ClientApp
vue create frontend
한 가지를 제외하고 모든 것이 완벽하게 작동한다.
앱 http://localhost:5000을 실행하고 Vue 라우터 링크를 클릭할 때마다 http://localhost:5000/정보라고 말하지만 새로 고침하면 예상 404가 표시됨
GET/정보할 수 없음
브라우저에 URL을 입력하고 직접 액세스한 경우에도 마찬가지다.
디폴트 리액션 앱이 이 문제에 직면하지 않고, 나는 두 ASP의 파일들 사이에서 모든 것을 비교했다는 것에 주목할 필요가 있다.이 도구를 사용하는 NET 앱에서 차이점을 찾을 수 없음
이제 Vue Router는 뒤에서 #!해시를 사용하기 때문에 Javascript로 경로를 처리한다. 그래서 ASP.NET 라우터는 URL을 AboutController@index와 일치시키려고 시도하지만, 이 경우 404는 존재하지 않는다.
조사 결과 나는 SPA 라우터에 와일드카드 폴백(fallback)을 설정해야 한다는 것이 밝혀졌다.Startup.cs
하지만 여기, 여기, 여기, 여기, 여기, 여기, 여기, 여기, 이 질문, 그리고 이 질문이app.UseMvc()
그리고 나는 그것을 가능하게 하지 않았다. 나는 사용하고 있다.app.UseEndpoints
대신에
나도 GitHub를 검색해봤는데 같은 결과가 나왔어.
이 답변은 내가 고수할 것을 권고한다.app.UseEndPoints
Microsoft 마이그레이션 가이드도 제공
Vue 라우터 설명서는 바로 이 문제에 대해 이야기하고 에 대한 해결책을 제안한다.NET 애플리케이션:web.config
여기에 나와 있는 답변과 같은 IIS의 경우 Linux 시스템에서 Kestrel 서버를 실행하고 있으므로 이 작업은 영향을 미치지 않음
여기 내 것이 있다.Startup.cs
파일
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
namespace spa
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// In production, the Vue files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "frontend/dist";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "frontend";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "serve:bs");
}
});
}
}
}
혹시 잊어버릴까 봐 쉽게 재생산할 수 있도록 이 앱을 여기 깃허브에 밀어넣었다.
어떻게 하면 이것과 같은 효과를 얻을 수 있을까?
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute("spa-fallback", "{*anything}", new { controller = "Home", action = "Index" });
});
사용.app.UseEndpoints
?
만약 이게 관련이 있다면, 여기 내 Vue 라우터가 있어.
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import NotFound from './views/NotFound.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import( /* webpackChunkName: "about" */ './views/About.vue')
},
{
path: '/forecast',
name: 'forecast',
component: () => import( /* webpackChunkName: "forecast" */ './views/Forecast.vue')
},
{
path: '*',
component: NotFound
}
]
})
이 템플릿을 사용해 보십시오. https://github.com/SoftwareAteliers/asp-net-core-vue-starter.그것은 최근에 업데이트되었고 지원되었다.Net Core 3.0 및 Vue CLI 3.0.
'programing' 카테고리의 다른 글
재료-UI의 탭과 반응 라우터 4의 통합? (0) | 2022.03.14 |
---|---|
어레이 속성을 중단하지 않고 TypeScript 딥 부분 매핑 유형을 구현하는 방법 (0) | 2022.03.14 |
Python 3에서 웹에서 파일 다운로드 (0) | 2022.03.14 |
Firebase 함수 다시 쓰기 및 vue 라우터와의 충돌 (0) | 2022.03.13 |
react js의 로컬 JSON 파일을 분석하려면 어떻게 해야 하는가? (0) | 2022.03.13 |