【问题标题】:Middleware doesn't work if i change endpoint如果我更改端点,中间件将不起作用
【发布时间】:2019-02-10 00:47:42
【问题描述】:

我的 NodeJs - Express 服务器有一个奇怪的问题,它充当我的移动应用程序的后端。 问题是我使用 axios 从前端向某些端点发送 post 请求,例如 checkmail、checkusername 并且它可以工作,但问题是它不适用于任何其他中间件功能。我从字面上复制了相同的检查邮件,只是使用了不同的路线,我得到状态 404,而使用 /checkmail 它可以工作! 另外, /login 不起作用,我使用的是 express。路由器在里面。 这是我的 app.js 代码:

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, () => { });

【问题讨论】:

  • 如果这些是发布请求,为什么不直接使用app.post()
  • 我也试过了,没用。我终于设法通过使用路由器和单独的控制器以及 /user/signup 来获得它们。

标签: javascript html node.js express middleware


【解决方案1】:

中间件接下来应该有第三个参数。

app.use("/checkmail", (req,res,next)=>{
//do something
})

【讨论】:

  • 如果我不想将请求传递给行中的下一个中间件,这有什么区别?
  • 设置一个 if 条件,如果是 res.send(200) else 将其传递给 next() 中间件。
【解决方案2】:

中间件必须有第三个参数,它是告诉应用程序转到下一个路由的回调。

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)
});

您可以在这里找到文档:https://expressjs.com/en/guide/error-handling.html

【讨论】:

  • 我要问你和我在下面问的同样的问题:如果我不想将请求传递给队列中的下一个中间件,这有什么区别? '对于从路由处理程序和中间件调用的异步函数返回的错误,您必须将它们传递给 next() 函数,Express 将在其中捕获并处理它们。 ' 这是来自 Express Documentation 我在响应 HTTP 请求的代码中没有错误处理任何内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-15
  • 2015-03-24
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
相关资源
最近更新 更多