在server.js(端口4000)中,我得到了以下路由:
// Auth middleware that checks if the user is logged in
const isLoggedIn = (req, res, next) => {
if (req.user) {
next();
}
else {
res.sendStatus(401);
}
}
app.get('/good', isLoggedIn, (req, res) => res.send(req.user));
甚至是这个:
app.get('/good', (req, res) => res.send(req.user));
最初,我想通过graphql查询获取用户数据,但无论如何。现在我想将此req.user数据放入我的react组件中,客户端位于端口3000上(我只想知道是否登录)。我尝试使用fetch和axios,但似乎没有看到req.user,(但是当我使用isLoggedIn函数时,它可以看到req.user为=“”,并且显示错误401,因为函数为
在http:// localhost:4000 /上正确显示了好数据。
更多详细信息:
const express = require('express');
const cors = require('cors');
const path = require('path');
const mongoose = require('mongoose');
require('dotenv').config();
const passport = require('passport');
require('./modules/auth');
const cookieSession = require('cookie-session');
// #6 Initialize an Express application
const app = express();
// app.use(cors());
app.use(
cors({
origin: "http://localhost:3000",
credentials: true
})
);
app.use(cookieSession({
name: 'session',
keys: ['key1', 'key2']
}))
app.use(passport.initialize());
app.use(passport.session());
app.get('/auth/google', passport.authenticate('google', { scope: ['profile','email'] }));
app.get('/auth/google/callback', passport.authenticate('google', {
successRedirect: 'http://localhost:4000/graphql',
failureRedirect: 'http://localhost:4000/graphql',
}));
// Auth middleware that checks if the user is logged in
const isLoggedIn = (req, res, next) => {
if (req.user) {
next();
}
else {
res.sendStatus(401);
}
}
app.get('/good', isLoggedIn, (req, res) => res.send(req.user));
// route for logging out
app.get('/logout', (req, res) => {
req.session = null;
req.logout();
res.redirect('/');
});
// Connect to Mongo and Apollo Server( skipped that, it's not the case)
// #7 Use the Express application as middleware in Apollo server( server was Apollo Server)
server.applyMiddleware({ app });
app.use(express.static('public'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'public', 'index.html'))
});
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
奖金: 这是ApolloServer的其他想法:
server.js(已跳过部分):
const { ApolloServer } = require('apollo-server-express');
const typeDefs = require('./modules/graphqlschemas/index');
const resolvers = require('./modules/resolvers/index');
// #5 Initialize an Apollo server
const server = new ApolloServer({
typeDefs: typeDefs,
resolvers: resolvers,
// context: ({ req, res }) => ({ req, res })
context: ({ req }) => ({
getUser: () => req.user,
logout: () => req.logout(),
})
});
用户解析器(带有当前用户查询的部分):
module.exports = {
Query: {
users: () => User.find({}),
currentUser: (parent, args, context) => context.getUser()
},
...