微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

订阅 Apollo 服务器不工作 - Nodejs/Express

如何解决订阅 Apollo 服务器不工作 - Nodejs/Express

我将 Apollo-serverNodejsexpress 一起使用 和

  1. 添加一本新书
  2. 我正在尝试使用 subscriptions 创建实时连接
  3. 但是我在 Graphiql 查询或我的 Client 中运行订阅后遇到的问题:
{
  "error": "Could not connect to websocket endpoint ws://localhost:4000/subscription. Please check if the endpoint url is correct."
}
  1. 我使用的是 Mozilla Firefox

  2. 这是我的代码

./index.js

const { ApolloServer,gql } = require('apollo-server-express')
const { resolvers,typeDefs } = require('./schema')
const { PubSub } = require('apollo-server')
const express = require('express')
const cors = require('cors')

const pubsub = new PubSub()
const app = express()
app.use(cors())

const server = new ApolloServer({
    resolvers,typeDefs,context: () => ({ pubsub })
})

server.applyMiddleware({ app,cors: true })

app.listen(4000,(res) => console.log('connected : http://localhost:4000/graphql'))

  1. 这是我的架构文件

./schema.js

const { gql } = require('apollo-server')

// my DB
const books = [
    { id: 1,title: 'the 7 habits',authorId: 1 },{ id: 2,title: 'the 9 Ahmed Googe',authorId: 2 },{ id: 3,title: 'How To use Google',{ id: 4,title: 'Go ahead',{ id: 5,title: 'Dont be stuped',authorId: 3 },{ id: 6,title: 'OMG',{ id: 7,title: 'Dont work for monty but work for life',]

const typeDefs = gql`
    type Query{
        books: [BookType]
    }
    type BookType {
        title: String
    }
    type Mutation{
        addBook(title: String): BookType
    }
    #Subscription 
    type Subscription{
        addBookSub:BookType
    }
`

const resolvers = {
    Query: {
        books: () => books,},Mutation: {
        addBook: (_,args,{ pubsub }) => {
            const newBook = { title: args.title }
            pubsub.publish('BOOK_ADDED',{ addBookSub: newBook })
            books.push(newBook)
            return newBook
        }
    },Subscription: {
        addBookSub: {
            subscirbe: (_,__,{ pubsub }) => pubsub.asyncIterator("BOOK_ADDED")
        }
    }
}

module.exports = { resolvers,typeDefs }
``

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。