【问题标题】:How to get cors to work properly with angular (apollo client ) and django/graphene如何让 cors 与 angular(apollo 客户端)和 django/graphene 一起正常工作
【发布时间】:2019-12-10 23:38:53
【问题描述】:

我正在尝试使用python-graphenedjango 构建一个应用程序,以在数据库端保存数据并在客户端使用角度。

我已经开发了这两个方面,并且它们独立运行良好,使用in-memory-web-api 的角度和使用insomnia 的石墨烯(Linux 的postman 样式应用程序)。

为了整合它们,我正在尝试使用apollo-angular。但是,请求返回 404。

我对 Web 开发还很陌生,所以我可能会遗漏一些琐碎的事情。

在网上搜索发现,因为服务器在http://localhost:8000上运行,而应用程序在http://localhost:4200上运行,所以我需要在服务器端设置CORS

我已按照manual上的说明进行操作:

  1. 通过pip install django-cors-headers安装corsheaders
  2. corsheaders 添加到INSTALLED_APPS
  3. MIDDLEWARE 上添加corsheaders.middleware.CorsMiddleware

但错误仍然存​​在。

那时我遇到了this thread,答案似乎是相关的。所以我:

  1. 在服务器上将CORS_ORIGIN_ALLOW_ALL = TrueCORS_ALLOW_CREDENTIALS = True 添加到settings.py
  2. MIDDLEWERE 中删除了django.middleware.clickjacking.XFrameOptionsMiddleware
  3. 在客户端的请求中添加了withCredentials标头。
  4. 已清理浏览器兑现数据和 cookie。

但错误仍然存​​在。

这是我的包含查询的组件:

import { Component, OnInit } from '@angular/core';
import { Patient } from '../patient';
import gql from 'graphql-tag';
import { Apollo } from 'apollo-angular';

const GET_PATIENTS = gql`
query all_patients {
    patients{
        id
        name
        age
    }
}
`;

export interface GetPatientsResponse {
    patients: Patient[];
    loading: boolean;
}

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
    patients: Patient[] = [];
    loading = true;

    constructor(private apollo: Apollo) { }

    ngOnInit() {
        this.apollo.watchQuery<GetPatientsResponse>({
            query: GET_PATIENTS
        }).valueChanges.subscribe((response) => {
            this.patients = response.data.patients;
            this.loading = response.data.loading;
        });
    }
}

另外,我已将这些添加到graphql.module.ts

const uri = 'http://localhost:8000/graphql/';

export function createApollo(httpLink: HttpLink) {
  return {
    link: httpLink.create({uri: 'http://localhost:8000/graphql/', withCredentials: true}),
    cache: new InMemoryCache(),
  };
}

我希望收到来自服务器的json 以及我的查询结果,结果却得到了404: http://localhost:8000/graphql/ Not Found

我错过了什么?

【问题讨论】:

  • 404 提示你的 django url 可能配置错误,能分享一下吗?
  • 感谢 Iain,我在 urls.py 下的 urlpatternspath('admin/', admin.site.urls)path('graphql/', csrf_exempt(GraphQLView.as_view(graphiql=True)))

标签: python django angular apollo-client graphene-python


【解决方案1】:

找了半天,看了this answer,终于发现了哪里出错了。

我同时使用angular-in-memory-web-api 并尝试将请求发送到我自己的服务器,这导致了错误。

通过从我的app.module.ts 中删除angular-in-memory-web-api,一切都按预期工作。

【讨论】:

    猜你喜欢
    • 2018-01-13
    • 2017-04-08
    • 2021-06-27
    • 2019-10-08
    • 2018-07-16
    • 2023-03-06
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多