【发布时间】:2019-12-10 23:38:53
【问题描述】:
我正在尝试使用python-graphene 和django 构建一个应用程序,以在数据库端保存数据并在客户端使用角度。
我已经开发了这两个方面,并且它们独立运行良好,使用in-memory-web-api 的角度和使用insomnia 的石墨烯(Linux 的postman 样式应用程序)。
为了整合它们,我正在尝试使用apollo-angular。但是,请求返回 404。
我对 Web 开发还很陌生,所以我可能会遗漏一些琐碎的事情。
在网上搜索发现,因为服务器在http://localhost:8000上运行,而应用程序在http://localhost:4200上运行,所以我需要在服务器端设置CORS。
我已按照manual上的说明进行操作:
- 通过
pip install django-cors-headers安装corsheaders。 - 将
corsheaders添加到INSTALLED_APPS。 - 在
MIDDLEWARE上添加corsheaders.middleware.CorsMiddleware。
但错误仍然存在。
那时我遇到了this thread,答案似乎是相关的。所以我:
- 在服务器上将
CORS_ORIGIN_ALLOW_ALL = True和CORS_ALLOW_CREDENTIALS = True添加到settings.py。 - 从
MIDDLEWERE中删除了django.middleware.clickjacking.XFrameOptionsMiddleware。 - 在客户端的请求中添加了
withCredentials标头。 - 已清理浏览器兑现数据和 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下的urlpatterns是path('admin/', admin.site.urls)和path('graphql/', csrf_exempt(GraphQLView.as_view(graphiql=True)))
标签: python django angular apollo-client graphene-python