【问题标题】:Next.js with express.js: Why is app.use not working?Next.js 与 express.js:为什么 app.use 不工作?
【发布时间】:2021-04-27 21:16:20
【问题描述】:

所以我正在使用 next.js 和自定义服务器 (express.js)。我有一些中间件(f.ex. const attachUser),我想在我的 API 端点中使用它们。但由于某种原因,我无法使用 app.use。

以下代码仅在我不使用 app.use(attachUser) 并手动将 attachUser 添加到每个端点时才有效。

require("dotenv").config();
const express = require("express");
const next = require("next");
const bodyParser = require("body-parser");
const cors = require("cors");

//next.js configuration
const dev = process.env.NODE_DEV !== "production";
const nextApp = next({
  dev
});
const port = 3000;
const handle = nextApp.getRequestHandler();

nextApp.prepare().then(() => {
      const app = express();

      app.use(bodyParser.json());
      app.use(bodyParser.urlencoded({
        extended: false
      }));
      app.use(cors());

      const attachUser = (req, res, next) => {
        const token = req.cookies["token"];

        if (!token) {
          return res.status(401).json({
            message: "Authentication invalid"
          });
        }
        const decodedToken = jwtDecode(token);

        if (!decodedToken) {
          return res.status(401).json({
            message: "There was a problem authorizing the request",
          });
        } else {
          req.user = decodedToken;
          next();
        }
      };

      //app.use(attachUser)

      app.get(
        "/api/savedItems", 
        attachUser,       //delete when app.use(attachUser) is used 
        async(req, res) => {
          try {
            //logic
          return res.json(itemData);
        } catch (err) {
          return res.status(400).json({
            error: err
          });
        }
      });

谁能告诉我我做错了什么?
顺便说一句,这是我的第一个项目。感谢任何改进代码的建议!非常感谢!

【问题讨论】:

    标签: javascript express next.js


    【解决方案1】:

    您不能在“try {}”和“catch{}”以及无用的“;”之间编写代码在“尝试{}”之后。您可以使用 JS lint 工具来检查代码

    【讨论】:

    • 你是说第 52 行?第 54 行有一个问题。
    • 是的,我错过了。那个分号和“return res.json(itemData);”令人不安
    猜你喜欢
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 2017-02-13
    • 1970-01-01
    • 2022-11-30
    • 2014-12-29
    相关资源
    最近更新 更多