change ./controllers/authentication.js
exports functions like this
const passport = require("passport");
const mongoose = require("mongoose");
const User = require("../schema/user");
const register = (req, res) => {
if (!req.body.name || !req.body.email || !req.body.password) {
return res.status(400).json({ message: "All fields required" });
}
const user = new User();
user.name = req.body.name;
user.email = req.body.email;
user.setPassword(req.body.password);
user.save((err) => {
if (err) {
res.status(404).json(err);
} else {
const token = user.generateJwt();
res.status(200).json({
token,
message: "User created!",
});
}
});
};
const login = (req, res) => {
if (!req.body.email || !req.body.password) {
return res.status(400).json({ message: "All fields required" });
}
passport.authenticate("local", (err, user, info) => {
let token;
if (err) {
return res.status(404).json(err);
}
if (user) {
token = user.generateJwt();
res.status(200).json({ token });
} else {
res.status(401).json(info);
}
})(req, res);
};
exports.register = register;
exports.login = login;
and change your App.js, remove /register
from route
require('dotenv').config();
const passport = require('passport');
require("./app_api/passport")
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
const userRoutes = require("./app_api/routes/index");
mongoose
.connect(
"mongodb://127.0.0.1:27017"
, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true}
) .then(() => {
console.log("Connected to database!");
})
.catch(() => {
console.log("Connection failed!");
});
app.use(passport.initialize());
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
next();
});
app.use("/", userRoutes);
module.exports = app;
change router like this :
const express = require("express");
const ctrlAuth = require("../../controllers/authentication");
const router = express.Router();
router.post('/register', ctrlAuth.register);
router.post('/login', ctrlAuth.login);
module.exports = router;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…