Apollo Angular 无法从 GraphQL/MongoDB 获取数据
Posted
技术标签:
【中文标题】Apollo Angular 无法从 GraphQL/MongoDB 获取数据【英文标题】:Apollo Angular failing to fetch data from GraphQL/MongoDB 【发布时间】:2021-09-18 06:13:00 【问题描述】:我是 GraphQL 和 Angular 的新手,我正在尝试构建一个简单的 Angular 组件,该组件使用 GraphQL 从 mongoose 数据库中获取数据。我设置了 GraphQL Express 服务器,它在 graphiql 和 Postman 中运行良好,但 Angular 组件的 http 请求始终失败。这是我的 graphql 模块:
import NgModule from '@angular/core';
import APOLLO_OPTIONS from 'apollo-angular';
import ApolloClientOptions, InMemoryCache from '@apollo/client/core';
import HttpLink from 'apollo-angular/http';
const uri = 'https://localhost:5001/graphql/'; // our GraphQL API
export function createApollo(httpLink: HttpLink): ApolloClientOptions<any>
return
link: httpLink.create( uri ),
cache: new InMemoryCache(),
;
@NgModule(
providers: [
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink],
,
],
)
export class GraphQLModule
和我的应用组件:
import Component, OnInit from '@angular/core';
import Apollo, gql from 'apollo-angular';
import Gadget from './models/Gadget';
const Get_MyGadgets = gql`
query
MyGadgets
id
productName
brand
cost
type
`;
@Component(
selector: 'app-root',
styleUrls: ['./app.component.scss'],
template: `
<table class="table table-dark table-striped">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Product Name</th>
<th scope="col">Brand</th>
<th scope="col">Cost</th>
<th scope="col">Type</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let gadget of allGadgets">
<td> gadget.id </td>
<td> gadget.productName </td>
<td> gadget.brand </td>
<td> gadget.cost </td>
<td> gadget.type </td>
</tr>
</tbody>
</table>
`
)
export class AppComponent implements OnInit
allGadgets: Gadget[] = [];
title = 'ang-graphql-apollo';
constructor(private apollo: Apollo)
ngOnInit(): void
this.apollo.watchQuery<any>(
query: Get_MyGadgets
)
.valueChanges
.subscribe(( data, loading ) =>
console.log(loading);
console.log(data);
this.allGadgets = data.MyGadgets;
);
还有我的 graphql express 服务器:
const express = require('express');
const ApolloServer = require('apollo-server-express');
const typeDefs = require('./typeDefs');
const resolvers = require('./resolvers');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');
const startServer = async () =>
const app = express();
const apolloServer = new ApolloServer(
typeDefs,
resolvers
);
await apolloServer.start();
apolloServer.applyMiddleware( app );
app.use((req, res) =>
res.send('Hello from express apollo server');
);
app.use(bodyParser.json());
app.use(cors());
await mongoose.connect('mongodb://localhost:27017/post_db',
useUnifiedTopology: true,
useNewUrlParser: true
);
mongoose.set('useFindAndModify', false);
console.log('Mongoose is connected...');
app.listen(5001, () => console.log('server is running at http://localhost:5001'));
startServer();
同样,express 服务器在 graphiql 和 Postman 中运行良好,但是当我在浏览器中打开应用程序时出现以下错误:
POST https://localhost:5001/graphql/ net::ERR_SSL_PROTOCOL_ERROR
core.js:6456 ERROR Error: Http failure response for https://localhost:5001/graphql/: 0 Unknown Error
at new ApolloError (index.js:26)
at QueryManager.js:536
at both (asyncMap.js:16)
at asyncMap.js:9
at new ZoneAwarePromise (zone.js:1387)
at Object.then (asyncMap.js:9)
at Object.error (asyncMap.js:17)
at notifySubscription (Observable.js:140)
at onNotify (Observable.js:179)
at SubscriptionObserver.error (Observable.js:240)
任何帮助将不胜感激。谢谢!
【问题讨论】:
【参考方案1】:您在本地主机中使用SSL
,这是不可能的。所以Angular
正在尝试通过https
与您的后端通信。
改变这个
const uri = 'https://localhost:5001/graphql/'; // our GraphQL API
到
const uri = 'http://localhost:5001/graphql/'; // our GraphQL API
你的错误应该消失了。
【讨论】:
感谢您的回复!我已将 uri 更改为 http,但现在我收到 400 错误“错误请求”。 这意味着您的请求正文与您的服务器期望的正文不匹配。我建议调试 Angular 作为 gql 主体发送的内容以上是关于Apollo Angular 无法从 GraphQL/MongoDB 获取数据的主要内容,如果未能解决你的问题,请参考以下文章
Apollo Angular 无法从 GraphQL/MongoDB 获取数据
Apollo Angular Add--无法读取 tsconfig.base.json
Apollo GraphQL:用于查询返回不同类型对象的模式?