You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

apollo-angular对接.NET Azure Function时出现疑似CORS错误

问题原因分析
  1. Azure Function CORS配置优先级问题:Azure Function自身的CORS配置(host.json或门户设置)会覆盖Startup.cs中通过AddCors注册的策略。HotChocolate的GraphQL Function基于Azure Function的HTTP触发器,因此Startup中的CORS配置不会生效。
  2. 预检请求未被正确处理:浏览器发起CORS预检请求(OPTIONS方法)时,若Azure Function未配置允许OPTIONS方法,会导致请求被拦截,进而客户端无法获取数据。
解决方案

方案一:通过host.json配置Azure Function全局CORS

在项目根目录的host.json文件中添加CORS配置,允许所需的源、方法和头:

{
  "version": "2.0",
  "cors": {
    "allowedOrigins": ["http://localhost:4200"], // 本地Angular开发地址,生产环境替换为实际域名
    "allowedMethods": ["GET", "POST", "OPTIONS"],
    "allowedHeaders": ["*"]
  }
}
  • 本地开发可临时用"*"允许所有源,生产环境必须指定具体域名以保证安全。

方案二:通过Azure门户配置CORS(针对已部署的Function)

  1. 登录Azure门户,找到你的Function App。
  2. 左侧导航栏选择API > CORS。
  3. 在允许的源中添加你的Angular应用地址(如http://localhost:4200),或勾选允许所有源(仅开发环境用)。
  4. 确保允许的方法包含GET、POST和OPTIONS,允许的头设为*。
  5. 保存配置。

额外检查点

  1. 验证GraphQL端点可达性:在浏览器中访问http://localhost:7071/api/graphql/,确认能正常加载GraphQL Playground,说明端点配置正确。
  2. 完善客户端错误处理:在ProductsService的订阅逻辑中添加错误捕获,便于排查问题:
this.apollo.watchQuery({ query: GET_PRODUCTS })
  .valueChanges.subscribe({
    next: ({ data }) => {
      const products = data.productsPaginated.nodes.map((val: any): Product => ({
        key: val.key,
        name: val.name,
        price: val.price,
        sale_price: val.sale_price,
        ratings: val.ratings
      }));
      this.#state.set({
        loading: false,
        products: products,
        error: null
      });
    },
    error: (err) => {
      console.error('GraphQL请求错误:', err);
      this.#state.set({
        loading: false,
        products: [],
        error: err.message
      });
    }
  });

内容的提问来源于stack exchange,提问作者Dr oscar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 21:04:56