我尝试将它与上下文连接一起使用,并将订阅参数添加到 Apollo Server 中,但它不起作用。我是第一次使用 Apollo 服务器订阅,我不知道错误是在服务器配置中还是在解析器中。我在查询或突变中没有问题,问题是订阅。
这是我的 index.js:
import express from 'express';
import { createServer } from 'http';
import { ApolloServer } from 'apollo-server-express';
import { typeDefs } from './data/schema';
import { resolvers } from './data/resolvers';
import cors from 'cors';
import jwt from 'jsonwebtoken';
const bodyParser = require('body-parser');
const PORT = process.env.PORT || 4004;
const app = express();
app.use(bodyParser.json());
app.use(cors());
const server = new ApolloServer({
typeDefs,
resolvers,
context: async({req, connection}) => {
console.log("Context connection", connection)
const token = req.headers['authorization'];
if(connection){
return connection.context;
} else {
if(token !== "null"){
try{
//validate user in client.
const currentUser = await jwt.verify(token, process.env.SECRET);
//add user to request
req.currentUser = currentUser;
return {
currentUser
}
}catch(err){
return "";
}
}
}
},
subscriptions: {
path: "/subscriptions",
onConnect: async (connectionParams, webSocket, context) => {
console.log(`Subscription client connected using Apollo server's built-in SubscriptionServer.`)
},
onDisconnect: async (webSocket, context) => {
console.log(`Subscription client disconnected.`)
}
}
});
我的突变:
mutation {
pushNotification(label:"My septh notification") {
label
}
}
我的查询:
query {
notifications {
label
}
}
我的订阅:
subscription {
newNotification {
label
}
}
错误是:
{
"error": {
"message": "Cannot read property 'headers' of undefined"
}
}
RISEBY
侃侃无极
相关分类