Angular应用程序通过HTTP请求NetCoreapi时被CORS策略阻止
创始人
2024-10-30 14:00:28
0

在Net Core api项目中的Startup.cs文件中添加以下代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAllOrigins", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyHeader()
                   .AllowAnyMethod();
        });
    });

    //其他代码
}

然后,在Net Core api控制器类中,使用[EnableCors]特性并指定策略名称:

[EnableCors("AllowAllOrigins")]
public class YourController : ControllerBase
{
    //其他代码
}

最后,在Angular应用程序中,使用HttpClient模块时,在请求头中添加以下代码:

import { HttpClient, HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, PATCH, DELETE, PUT, OPTIONS'
  })
};

@Injectable()
export class YourService {
  constructor(private http: HttpClient) {
  }

  yourFunction() {
    return this.http.get('https://your-net-core-api-url', httpOptions)
               .pipe(map(res => res.json()));
  }
}

相关内容

热门资讯

德扑之心免费透视!pokemm... 德扑之心免费透视!pokemmo手机辅助软件(透视)技巧-都是解密真的是有挂1、完成pokemmo手...
佛手在线大菠萝为什么都输!we... 您好,佛手在线大菠萝为什么都输这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302...
wepoker有辅助工具吗!h... wepoker有辅助工具吗!hhpoker德州挂真的有吗(透视)脚本-切实揭幕是真的挂1、让任何用户...
wepoker有没有机器人!h... wepoker有没有机器人!hh poker软件(透视)教程-好像普及真的是有挂1、完成wepoke...
wepoker轻量版有透视吗!... wepoker轻量版有透视吗!aapoker怎么拿好牌(透视)插件-切实普及是有挂1、进入到wepo...
pokemmo手机辅助软件!w... pokemmo手机辅助软件!wpk软件是正规的吗(透视)工具-都是总结真的是有挂1)pokemmo手...
wepoker俱乐部辅助!po... wepoker俱乐部辅助!pokeplus脚本(透视)技巧-其实科普是有挂1、wepoker俱乐部辅...
wepoker破解器有用吗!w... wepoker破解器有用吗!wepoker私人局规律(透视)教程-都是揭露是有挂1、这是跨平台的we...
wejoker辅助机器人!德州... wejoker辅助机器人!德州真人透视脚本(透视)神器-都是曝光存在有挂德州真人透视脚本破解侠是真的...
wpk有透视吗!来玩app破解... wpk有透视吗!来玩app破解(透视)挂-其实解迷存在有挂1、来玩app破解模拟器是什么优化,来玩a...