javascript - 尝试发送 POST 请求时收到 404 错误

标签 javascript node.js api express

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

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

然后我明白了

error

这是我的 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;

最佳答案

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

请参阅 here 中的文档- 来自提供的链接:

Writing error handlers Define error-handling middleware functions in the same way as other middleware functions, except error-handling functions have four arguments instead of three: (err, req, res, next). For example:

// 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响应。您应该将其设置为适当的错误处理程序,或者将其删除。

关于javascript - 尝试发送 POST 请求时收到 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53806322/

相关文章:

javascript - 如何在 swaggerexpress 中附加中间件,如express-validator

node.js - 在 node.js 中使用 Node 纤程时,在 GC 期间 V8 内部出现 "Fatal error"

javascript - 等待的 Promises 创建 Array.map 返回 <pending>

javascript - 为什么我的 RestFul API 与express和nodejs每天都会崩溃?

javascript - AngularJS - 使用 ng-include append html

javascript - 如何将 put 请求与 axios 连接以使其在前端工作?

javascript - 如何动态添加列到 Bootstrap Vue 表

javascript - 当使用 Angular 1.6 ng-switch 在过滤器列表中显示键和值时

java - Picasa API - URL 不适用于标签

.net - 是否有任何 Robocopy 的 API 包装器?