zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Spring Boot JDBC 使用教程
    Spring Boot FreeMarker 使用教程
    椭圆曲线ECC ECDH原理&& javacard实现
    java中的强制类型转换:int和byte
    JUnit学习
    java异常处理
    Maven使用
    哈希表问题
    计数排序
    链表Linked List
  • 原文地址:https://www.cnblogs.com/donaldtdz/p/7882225.html
Copyright © 2011-2022 走看看