2

我是 GraphQL 和 Angular 的新手,我正在尝试构建一个简单的 Angular 组件,该组件使用 GraphQL 从猫鼬数据库中获取数据。我设置了 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)

任何帮助,将不胜感激。谢谢!

4

1 回答 1

0

SSL在本地主机中使用这是不可能的。Angular尝试https通过.

改变这个

const uri = 'https://localhost:5001/graphql/'; // our GraphQL API

const uri = 'http://localhost:5001/graphql/'; // our GraphQL API

你的错误应该消失。

于 2021-07-08T13:40:34.250 回答