【问题标题】:Apollo Server Express + Subscriptions errorApollo Server Express + 订阅错误
【发布时间】:2020-04-02 21:45:59
【问题描述】:

我正在开发一个 Express 后端项目 (Apollo Server + Express + GraphQL),它的前端部分是用 React 制作的。

我想根据数据库更改在前端进行一些更改。例如,当创建用户时。我正在阅读一些文件,直到到达Apollo documentation regarding React subscriptions

然后我读了Apollo Boost migration to set up client manually,因为它不支持订阅。然后我继续前进到setting up Express to support subscriptions,但我的代码不起作用。

这是我在控制台中遇到的错误:

app.use(process.env.GRAPHQL_PATH, _bodyParser["default"].json(), (0, _apolloServerExpress.graphqlExpress)({

TypeError: (0 , _apolloServerExpress.graphqlExpress) 不是函数 在对象。 (C:\Web\backend\src/index.js:83:5)

这是第 83 行:graphqlExpress({ schema }),我在下面的右侧做了评论。

首先我的快递是这样的:

import cors from 'cors';
import express from 'express';
import jwt from 'jsonwebtoken';
import mongoose from 'mongoose';
import { ApolloServer, AuthenticationError } from 'apollo-server-express';
import errorMessages from './mensajes/errors.json';
require('dotenv').config();

import schemas from './schemas';
import resolvers from './resolvers';

import userModel from './models/usuario';

const app = express();

app.use(cors());

const getUser = async (req) => {
    const token = req.headers.token;

    if (token) {
        try {
            return await jwt.verify(token, process.env.JWT_SECRET);
        } catch (e) {
            throw new AuthenticationError(mensajesError.sesionExpirada);
        }
    }
};

const server = new ApolloServer({
    typeDefs: schemas,
    resolvers,
    context: async ({ req }) => {
        if (req) {
            const me = await getUser(req);

            return {
                me,
                models: {
                    userModel
                },
            };
        }
    }
});

server.applyMiddleware({ app, path: process.env.GRAPHQL_PATH });

const options = { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
    useCreateIndex: true 
};

app.listen(process.env.PORT, () => {
    console.clear();
    mongoose.connect('mongodb://.../sandbox', options)
    .then(() => {
        console.log(`Database and server running on port ${process.env.PORT}`);
    })
    .catch(error => {
        console.error(`The server or the database cannot start:`);
        console.error(error);
    });
});

然后我根据之前的 Apollo 文档把我的代码改成了:

import { graphqlExpress } from 'apollo-server-express';
import { createServer } from 'http';
import { execute, subscribe } from 'graphql';
import { PubSub } from 'graphql-subscriptions';
import { SubscriptionServer } from 'subscriptions-transport-ws';
require('dotenv').config();

import schema from './schemas';
import resolvers from './resolvers';

import userModel from './models/usuario';

const app = express();

app.use(
    process.env.GRAPHQL_PATH,
    bodyParser.json(),
    graphqlExpress({ schema }) // <-- Line 83
);

const pubsub = new PubSub();
const server = createServer(app);

server.listen(process.env.PORT, () => {
    new SubscriptionServer({
        execute,
        subscribe,
        schema,
    }, {
        server,
        path: '/subscriptions'
    });
});

当然缺少很多信息,但我想我仍然必须了解这一点。你明白那个错误吗?任何 cmets 都表示赞赏。

【问题讨论】:

    标签: node.js reactjs express graphql apollo


    【解决方案1】:

    我也尝试过使用subscriptions-transport-ws 但由于这个issue,它不起作用。

    这是一个适合我的配置。

    const http = require('http');
    const { ApolloServer } = require('apollo-server-express');
    const express = require('express');
    const graphQlSchema = require("./graphql/schema");
    const grapgQlResolvers = require("./graphql/resolvers");
    
    const PORT = 3000;
    const app = express();
    
    const server = new ApolloServer({ 
      typeDefs: graphQlSchema, 
      resolvers: grapgQlResolvers,
    });
    
    server.applyMiddleware({ app, cors: true })
    
    const httpServer = http.createServer(app);
    server.installSubscriptionHandlers(httpServer);
    
    httpServer.listen(PORT, () => {
        console.log(`? Server ready at http://localhost:${PORT}${server.graphqlPath}`)
        console.log(`? Subscriptions ready at ws://localhost:${PORT}${server.subscriptionsPath}`)
    })
    

    【讨论】:

      猜你喜欢
      • 2020-08-11
      • 2018-06-17
      • 2020-04-23
      • 2017-09-01
      • 2017-09-19
      • 2021-01-18
      • 2020-10-08
      • 2018-10-21
      • 2019-12-05
      相关资源
      最近更新 更多