ABP .Net Core API和Angular前端APP独立部署跨域问题(No Access-Control-Allow-Origin) - Go语言中文社区

ABP .Net Core API和Angular前端APP独立部署跨域问题(No Access-Control-Allow-Origin)


前言:

通过ABP官网(https://aspnetboilerplate.com)下载ASP.NET Core 2.x + Angular模板项目是按ReStful风格架构Web API和angular前端是分开独立部署的,我一开始分开部署到IIS后,前端访问API会产生跨域限制访问的问题,通过查阅代码,其实ABP框架自带跨域设置访问,只需要配置一下就可以了,步骤如下:

 

一 IIS部署

通过ABP官网模板创建项目,然后分别打包前端和后端程序发布到IIS:

我的后端发布到:http://localhost:8060/

我的前端发布到:http://localhost:8080/

 

F12 报错 不允许跨域访问:Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

 

二 配置说明

通过查看代码有两个配置的地方:

1. 前端配置在src/assets/appconfig.json

{
  "remoteServiceBaseUrl": "http://localhost:8060",
  "appBaseUrl": "http://localhost:8080"
}

remoteServiceBaseUrl 远程访问API URL, appBaseUrl 自身部署后的URL

 

2. 后端配置在Host项目 appsettings.json

"App": {
    "ServerRootAddress": "http://localhost:8060/",
    "ClientRootAddress": "http://localhost:8080/",
    "CorsOrigins": "http://localhost:8080/"
  }

ClientRootAddress 为客户端站点配置, CorsOrigins 为允许跨域客户端站点配置,可以有多个用逗号分开,配置在Startup.cs里进行配置

// Configure CORS for angular2 UI
services.AddCors(options =>
{
  options.AddPolicy(DefaultCorsPolicyName, builder =>
    {
       // App:CorsOrigins in appsettings.json can contain more than one address separated by comma.
       builder
       .WithOrigins(_appConfiguration["App:CorsOrigins"].Split(",", StringSplitOptions.RemoveEmptyEntries)
       .Select(o => o.RemovePostFix("/"))
       .ToArray())
       .AllowAnyHeader()
       .AllowAnyMethod();
     });
});

 

三 运行

配置后再次访问客户端 访问成功

 

如果配置没有问题,在PUT和DELETE请求仍然包跨域问题,很有可能是服务器限制了谓词访问,请参考博客:http://www.cnblogs.com/donaldtdz/p/8094300.html

如想前后端集成一起部署请查博客:http://www.cnblogs.com/donaldtdz/p/7882316.html

 

转载于:https://www.cnblogs.com/donaldtdz/p/7882225.html

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_30294021/article/details/99404514
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-08 11:30:31
  • 阅读 ( 1227 )
  • 分类:前端

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢