【问题标题】:receiveing 404 error when trying to send a POST request尝试发送 POST 请求时收到 404 错误
【发布时间】:2018-12-16 20:44:23
【问题描述】:

我正在尝试使用 node.js 设置 API,并且在我的 app.js 类中我正在处理请求错误,如果出现问题,我会返回 404,现在这就是我的问题,我看不到我如何请求任何东西错了,我仍然收到 404 错误,我试图向我的 API 发送一个发布请求,就像这样:

{
    "name":"Harry Potter 5",
    "price":"12.99"
}

那我明白了

这是我的 app.js

const express = require('express');
const app = express();
const morgan = require('morgan');
const productRoutes = require('./api/routes/product');
const orderRoutes = require('./api/routes/order');
const bodyParser = require('body-parser');

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({
    extended:false
}));
app.use(bodyParser.json());
app.use((req, res, next) => {
    const error = new Error("Not found");
    error.status = 404;
    next(error);
  });

  app.use((error, req, res, next) => {
    res.status(error.status || 500);
    res.json({
      error: {
        message: error.message
      }
    });
  });
app.use('/products', productRoutes);
app.use('/orders', orderRoutes);

module.exports = app;

这是我的 product.js

const express = require('express');
const router = express.Router();

router.get('/', (req, res, next) => {
    res.status(200).json({
        message: 'Handling GET requests to /products'
    });
});

router.post('/', (req, res, next) => {
    const product = {
        name: req.body.name,
        price: req.body.price
    };
    res.status(201).json({
        message: 'Handling POST requests to /products',
        createdProduct: product
    });
});

router.get('/:productId', (req, res, next) => {
    const id = req.params.productId;
    if (id === 'special') {
        res.status(200).json({
            message: 'You discovered the special ID',
            id: id
        });
    } else {
        res.status(200).json({
            message: 'You passed an ID'
        });
    }
});

router.patch('/:productId', (req, res, next) => {
    res.status(200).json({
        message: 'Updated product!'
    });
});

router.delete('/:productId', (req, res, next) => {
    res.status(200).json({
        message: 'Deleted product!'
    });
});

module.exports = router;

【问题讨论】:

    标签: javascript node.js api express


    【解决方案1】:

    这是因为您将所有内容都设置为错误输出:)

    查看来自here 的文档 - 来自提供的链接:

    编写错误处理程序定义错误处理中间件函数 与其他中间件功能相同,除了错误处理 函数有四个参数而不是三个:(err, req, res, next)。 例如:

    // pay attention to err param
    app.use(function (err, req, res, next) {
       console.error(err.stack)`  
       res.status(500).send('Something broke!')
    })
    

    在你的代码中你有这个位:

    app.use((req, res, next) => {
        const error = new Error("Not found");
        error.status = 404;
        next(error);
      });
    

    它告诉 express 每个请求都应该用 404 响应。您应该将其设置为适当的错误处理程序,或者将其删除。

    【讨论】:

      【解决方案2】:

      这是因为任何请求都会执行 404 处理程序。

      看看你的代码的这个缩短版本:

      const express = require('express');
      const app = express();
      const bodyParser = require('body-parser');
      
      app.use(bodyParser.urlencoded({
          extended:false
      }));
      app.use(bodyParser.json());
      
      app.use((req, res, next) => {
        console.log("Got into 404 handler");
      
        const error = new Error("Not found");
        error.status = 404;
        next(error);
      });
      
      app.use((error, req, res, next) => {
        console.log("Got into 500 handler");
      
        res.status(error.status || 500);
        res.json({
          error: {
            message: error.message
          }
        });
      });
      app.use('/products', (req, res, next) => {
        console.log("Got into 200 handler");
      
        res.status(200).end();
      });
      
      app.listen(8080);
      

      它在每次请求时打印“Got into 404 handler”。现在,如果您以这种方式注释掉 404 回调:所有请求都会经过 500 和 200 回调:

      const express = require('express');
      const app = express();
      const bodyParser = require('body-parser');
      
      app.use(bodyParser.urlencoded({
          extended:false
      }));
      app.use(bodyParser.json());
      
      /* there used to be the 404 callback here */
      
      app.use((error, req, res, next) => {
        console.log("Got into 500 handler");
      
        res.status(error.status || 500);
        res.json({
          error: {
            message: error.message
          }
        });
      });
      app.use('/products', (req, res, next) => {
        console.log("Got into 200 handler");
      
        res.status(200).end();
      });
      
      app.listen(8080);
      

      现在在您的具体问题中,下面的代码可以工作(我只是交换了处理程序的顺序):

      const express = require('express');
      const app = express();
      const bodyParser = require('body-parser');
      
      app.use(bodyParser.urlencoded({
          extended:false
      }));
      app.use(bodyParser.json());
      
      app.use('/products', (req, res, next) => {
        console.log("Got into 200 handler");
      
        res.status(200).end();
      });
      
      app.use((req, res, next) => {
        console.log("Got into 404 handler");
      
        const error = new Error("Not found");
        error.status = 404;
        next(error);
      });
      
      app.use((error, req, res, next) => {
        console.log("Got into 500 handler");
      
        res.status(error.status || 500);
        res.json({
          error: {
            message: error.message
          }
        });
      });
      
      
      app.listen(8080);
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2017-06-22
        • 2021-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-03
        • 2020-11-20
        • 2018-03-25
        • 1970-01-01
        相关资源
        最近更新 更多