Using postman
, when attempting to POST
for user registration with the endpoint
"http://localhost:3000/register?name=USER1&<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="61f4fcf0f8fdac8484948795c0948494829798fdfcc7faf6f4">[email protected]</a>&password=pass1"
, it appears that the routing is not functioning correctly. What could be causing this issue?
Errors: Postman displays Cannot POST /register
. Apart from that, no errors are observed and the server operates fine on port 3000.
App.js
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("/register", userRoutes);
module.exports = app;
./routes/index.js
const express = require("express");
const ctrlAuth = require("../../controllers/authentication");
const router = express.Router();
router.post('/register', function(req, res){ctrlAuth.register});
router.post('/login', function(req, res){ctrlAuth.login});
module.exports = router;
./controllers/authentication.js
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!"
});
}
});
};
module.exports = {
register
};
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);
};
module.exports = {
login
};