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

Django后端无法向Angular前端返回JSON数据问题排查

Django + Angular 跨域请求问题

我有一个Web项目,后端基于Django,前端基于Angular。

启动信息

  • 后端启动命令:
    python3 manage.py runserver 192.168.1.195:8080
    
  • 前端启动命令:
    ng serve --host 192.168.1.195
    
    前端运行在4200端口。

Django CORS配置

settings.py中的CORS_ORIGIN_WHITELIST配置如下:

CORS_ORIGIN_WHITELIST = (
    'http://192.168.1.195:8080',
    'http://localhost:8081',
    'http://192.168.1.195:4200',
    'http://127.0.0.1:4200',

)

前端相关代码

service.ts

var apiUrl = "http://192.168.1.195:8080";

var httpLink = {
//  getAllEmployee: apiUrl + "/api/employee/getAllEmployee",
  getAllEmployee: apiUrl + "/api/hosts_groups",
  deleteEmployeeById: apiUrl + "/api/employee/deleteEmployeeById",
  getEmployeeDetailById: apiUrl + "/api/employee/getEmployeeDetailById",
  saveEmployee: apiUrl + "/api/employee/saveEmployee"
}

@Injectable({
  providedIn: 'root'
})
export class HttpProviderService {

  constructor(private webApiService: WebApiService) { }

  public getAllEmployee(): Observable<any> {
    return this.webApiService.get(httpLink.getAllEmployee);
  }

home.component.ts

@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
    closeResult = '';
    employeeList: any = [];
    constructor(private router: Router, private modalService: NgbModal,
        private toastr: ToastrService, private httpProvider : HttpProviderService) { }
    ngOnInit(): void {
        this.getAllEmployee();
    }
    async getAllEmployee() {
        this.httpProvider.getAllEmployee().subscribe((data : any) => {
            if (data != null && data.body != null) {
                var resultData = data.body;
                if (resultData) {
                    this.employeeList = resultData;
                }
            }
        },
        (error : any)=> {
            if (error) {
                if (error.status == 404) {
                    if(error.error && error.error.message){
                        this.employeeList = [];
                    }
                }
            }
        });
    }

测试结果

  • 直接访问http://192.168.1.195:8080/api/hosts_groups时,Django正常返回JSON,后端控制台输出:
    "GET /api/hosts_groups HTTP/1.1" 200 85
    
  • 访问前端页面http://192.168.1.195:4200时,无法获取JSON数据,但后端控制台显示:
    "OPTIONS /api/hosts_groups HTTP/1.1" 200 0
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 16:00:34