I have a strange problem with my NodeJs - Express server which serves as a back-end for my mobile application. The thing is that i send post requests to some endpoints like checkmail, checkusername from front-end using axios and it works, but the problem is it doesn't work for any other middleware function. I literally copied the same checkmail and just used different route and I get status 404 while with /checkmail it works! Also, the /login does not work, im using express. Router in there. Here is my app.js code:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
var cors = require("cors");
const User = require("./models/user");
var AuthController = require('./auth/authController');
const app = express();
let server = require("http").Server(app);
app.use(cors());
app.use(
bodyParser.urlencoded({
extended: true
})
);
app.use(bodyParser.json());
//Check if e-mail is aready in use, return "success" if not
app.use("/signup", (req, res) => {
User.findOne({
email: req.body.email
},
function (err, user) {
if (user) {
res.send("error");
} else {
res.send("success");
}
}
);
});
//Check if e-mail is aready in use, return "success" if not
app.use("/checkmail", (req, res) => {
User.findOne({
email: req.body.email
},
function (err, user) {
if (user) {
res.send("error");
} else {
res.send("success");
}
}
);
});
app.use('/login', AuthController);
const port = process.env.PORT || 8500;
server.listen(port, () => { });
Middleware should have third parameter next.
app.use("/checkmail", (req,res,next)=>{
//do something
})
You must have third parameter in middleware, it's callback to tell application go to next route.
app.use('/signup', (req, res, next) => { // Normal middleware, it must have 3 parameters
User.findOne({
email: req.body.email
},
function (err, user) {
if (user) {
next(new Error('Some thing wrong')); // Failed, we will go to error-handling middleware functions
} else {
next(); // Success and we will go to next route
}
}
);
});
app.get('/signup', (req, res, next) => { // This is "next route"
res.send('Yay, welcome to signup')
});
app.use((err, req, res, next) => { // error-handling middleware function, It must have 4 parameters
res.status(500).send(err)
});
You can find document in here: https://expressjs.com/en/guide/error-handling.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.