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

Angular SSR配置代理后无法获取API数据的问题求助

Angular SSR请求Strapi无数据,报错Cannot read properties of undefined (reading 'attributes')

核心问题分析

你的问题根源是**server.ts中的代理配置错误**,导致服务器端请求没有被转发到Strapi,反而拿到了无效响应(比如页面HTML或空数据),最终触发data.data为undefined的报错。同时缺少数据容错逻辑,放大了问题影响。


解决方案

1. 修复server.ts的代理配置

你之前的写法只是在回调里创建了代理中间件,但没有实际执行它,导致请求完全没被代理。正确写法如下:

import { createProxyMiddleware } from 'http-proxy-middleware';

// 其他server.ts代码...

// 直接将代理中间件传给server.use,无需嵌套回调
server.use('/api', createProxyMiddleware({
  target: 'http://localhost:8000',
  changeOrigin: true,
  logLevel: 'debug',
}));

启动SSR后,终端如果出现[HPM] Proxy created: /api -> http://localhost:8000的日志,说明代理已生效。

2. 确保服务器端请求路径正确

服务器端运行时,不能直接用浏览器的相对路径逻辑,需要明确请求SSR服务器的代理路径:

import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { isPlatformServer } from '@angular/common';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class HomeService {
  constructor(
    private http: HttpClient,
    @Inject(PLATFORM_ID) private platformId: object
  ) {}

  getHomeContent() {
    // 服务器端请求自己的SSR端口,通过代理转发到Strapi
    const baseUrl = isPlatformServer(this.platformId) ? 'http://localhost:4000' : '';
    return this.http.get(`${baseUrl}/api/home`);
  }
}

注:4000替换成你的Angular SSR服务器实际端口

3. 添加数据容错逻辑

即使代理修复,也要避免API返回异常导致页面崩溃:

private getHomePageContentSuccess(data: IDataPayload<IHomePayload>): void {
  // 用可选链判断数据是否存在,同时添加兜底值
  this.homeContent = data?.data?.attributes || {} as IHomePayload;
  
  // 可选:添加日志排查问题
  if (!data?.data?.attributes) {
    console.warn('首页数据缺失或格式错误:', data);
  }
}

4. 验证服务器端响应

在请求的订阅逻辑中添加日志,确认服务器端是否拿到了Strapi的正确数据:

this.homeService.getHomeContent().subscribe({
  next: (res) => {
    // 服务器端运行时,日志会打印在终端
    console.log('服务器端API响应:', res);
    this.getHomePageContentSuccess(res);
  },
  error: (err) => {
    console.error('服务器端请求失败:', err);
  }
});

内容的提问来源于stack exchange,提问作者Justin Ledoux

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:30:51