Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
62 views
in Technique[技术] by (71.8m points)

javascript - routing does not work correctly, why is that?

I used postman to post to register a user with "http://localhost:3000/register?name=USER1&[email protected]&password=pass1" and seems like it doesn't get routed correctly. What could be the problem?

Errors: Postman shows Cannot POST /register. Other than that, no errors, server runs ok in 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
    };
question from:https://stackoverflow.com/questions/65846816/routing-does-not-work-correctly-why-is-that

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...