После поиска множества ответов на одну и ту же проблему, ни один из ответов не работает для меня. Поэтому я надеюсь, что смогу получить некоторую помощь. В Routes / profile.js я делаю запрос get на localhost: 8081 / profile, который выдает мне ошибку. Я использую Express и mongodb.
server.js
Примечание:
- authRoutes и profileRoutes используются в качестве промежуточного программного обеспечения для маршрутов
const express = require("express");
const app = express();
const authRoutes = require("./routes/authorize");
const profileRoutes = require("./routes/profile");
require("dotenv/config");
const PORT = process.env.PORT || 8081;
const cors = require("cors");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const cookieSession = require("cookie-session");
const passport = require("passport");
const keys = require("./config/key.js");
const passportSetup = require("./config/passport.js");
app.use("/auth", authRoutes);
app.use("/profile", profileRoutes);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//Initialize passport
app.use(passport.initialize());
app.use(passport.session());
app.use(
cookieSession({
maxAge: 24 * 60 * 60 * 1000,
keys: [keys.session.cookieKey]
})
);
app.use(cors());
app.use(morgan("combined"));
mongoose.connect(
process.env.DB_CONNECTION,
{
useNewUrlParser: true,
useUnifiedTopology: true
},
() => console.log("mongo atlas")
);
app.listen(PORT, () => {
console.log(`Server is on port ${PORT}`);
});
passport.js
const passport = require("passport");
const GoogleStratedy = require("passport-google-oauth20");
const keys = require("./key.js");
const User = require("../models/userModel");
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id).then(user => {
done(null, user);
});
});
passport.use(
new GoogleStratedy(
{
//options for the google strategy
callbackURL: "/auth/google/redirect",
clientID: keys.google.clientID,
clientSecret: keys.google.clientSecret
},
(accessToken, refreshToken, profile, done) => {
//passport callback function
console.log("passport callback fired");
//Check if user already exist in Db
User.findOne({ googleId: profile.id }).then(currentUser => {
if (currentUser) {
//already have user
console.log(`user is: ${currentUser} ALREADY REGISTERED`);
done(null, currentUser);
} else {
//create new user
new User({
username: profile.displayName,
googleId: profile.id
})
.save()
.then(newUser => {
console.log(`new user created ${newUser}`);
done(null, newUser);
});
}
});
}
)
);
Routes / authorize.js
const express = require("express");
const router = express.Router();
const passport = require("passport");
//auth login
router.get("/login", (req, res) => {
res.send({
message: `Hello ${req.body.email}! Your user was registered`
});
});
//auth logout
router.get("/logout", (req, res) => {
res.send("it works");
});
//auth with google
router.get(
"/google",
passport.authenticate("google", {
scope: ["profile"]
})
);
router.get("/google/redirect", passport.authenticate("google"), (req, res) => {
res.redirect("/profile");
});
module.exports = router;
Routes / profile.js Это для перенаправления API
const router = require("express").Router();
const passport = require("passport");
router.get("/", (req, res) => {
console.log(req.user.username);
});
module.exports = router;
userModel.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: String,
googleId: String
});
const User = mongoose.model("user", userSchema);
module.exports = User;