asp.net - 将 WebApi 从 Angular 分离到两个不同的项目
问题描述
现在我默认使用 VS 中的 webApi 和 Angular 应用程序这样一个项目。我想把它分成两个项目。我从我的 StarUP 文件中删除了所有与 SPA 相关的内容。我用命令运行 Angular 部分,nmp run start
它在 4200 中运行。我${environment.apiUrl}/api
通过这种方式为我的 api 请求添加
async loginUser(login: Login): Promise<any> {
return this.http.post(`${environment.apiUrl}/api/${environment.apiVersion}/userAuth/login`, login).toPromise();
我在网络中看到Request URL: https://localhost:44347/api/v1.0/userAuth/login
但我有cors错误。我的标题在网络中看起来像这样。
当我回到一个单体项目 angular 和 webApi 并运行它时。在网络中,我的标题看起来像这样。
正如您在第一种情况下看到的那样,我没有完整的标题。我如何才能将我的 Angular 应用程序与 web api 分开运行这样一个完整的单一应用程序?谢谢
解决方案
如果您作为 Asp.Net Core 或 5+ 应用程序运行,您有两种方法:
1 -在您的 Web api 上启用 CORS
当您从生产中的不同服务器提供 api 和 angular 应用程序时,这是理想的选择。
在开发中,您的 URL 将是:
Angular:https://localhost:4002(您将在浏览器中使用这个)
WebApi:https://localhost:44347
Statup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("Any",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
options.AddPolicy("Production",
builder =>
{
builder.WithOrigins("https://your-angular-domain.com", "https://your-other-domain.com");
});
}
// Your other services
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseCors("Any"); // Allow any origin
}
else
{
app.UseCors("Production"); // Only allow specific origins
app.UseHsts();
app.UseHttpsRedirection();
}
// Your other middlewares....
}
2.使用Spa中间件
当您从生产环境中的同一台服务器上为您的 WebAPi 和 Angular 应用程序提供服务时,这是理想的选择。
在开发中,您的 URL 将是:
Angular: https://localhost:4002
WebApi: https://localhost:44347 (您将在浏览器中使用这个)
Statup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Your other middlewares....
app.UseSpa(spa =>
{
if (env.IsDevelopment()) // In production your angular app and web api will already be at the same server, or you should enable CORS
{
spa.UseProxyToSpaDevelopmentServer("http://localhost:4001");
}
});
}
推荐阅读
- java - Java按字母顺序排序字符串并保持ASCII顺序
- intellij-idea - Flatpak Intellij Idea - 颠覆可执行文件的问题
- graphql - 在 Netlify 上部署会引发我的 GraphQL/Gatsby/Contentful 查询错误,需要不必要的查询参数
- django - 在 Django 中测试 RESTful API URL 时出现上下文错误
- symfony - 最佳实践 - 如何响应不同的实体视图以提高 RESTful API 的性能(Symfony 4)
- javascript - 覆盖 Highcharts 中自动生成的 Y 轴绘图区域值
- php - TDAmeritrade API 身份验证错误:无法解析 API 密钥变量 request.header.un
- angular - 我可以将 ng 模板用于单独的组件并在其他 html 中使用其模板引用吗?
- c++ - ml::KNearest->findNearest() 类别标签更改时结果不一致
- java - 停止 Maven 安装