我的后端工作有问题.老实说,它甚至没有加载,我得到的日志服务器已经启动,但进入http://localhost:5000/api/items加载无限期。我不知道我做错了什么。
这是我的server.js
const express = require('express');
const bodyParser = require('body-parser');
const routes = require('./items-routes');
const server = express();
server.use(bodyParser.json);
server.use('/api/items', routes);
const port = 5000;
try {
  server.listen(port);
  console.log(`Listening on port ${port}`);
} catch (error) {
  console.log(error.message);
}这是我的物品
const express = require('express');
const itemsController = require('./items-controller');
const router = express.Router();
router.get('/', itemsController.getItems);
router.post('/:iid', itemsController.createItem);
module.exports = router;最后,我的项目-Controler.js
const Item = require('./items-schema');
const items = [
  {
    title: 'This is a title',
    description: 'This is a description',
  },
  {
    title: 'This is another title',
    description: 'This is another description',
  },
  {
    title: 'This is a third title',
    description: 'This is a third description',
  },
];
const getItems = async (req, res, next) => {
  res.json({
    items: items.map((item) => {
      item.toObject({ getters: true });
    }),
  });
  console.log('These are the ITEMS!');
};
const createItem = async (req, res, next) => {
  const { title, description } = req.body;
  const createdItem = new Item({
    title,
    description,
  });
  try {
    items.push(createItem);
    console.log('You are posting an ITEM!');
  } catch (error) {
    return next(error);
  }
  res.status(201).json({ item: createdItem });
};
exports.getItems = getItems;
exports.createItem = createItem;我最初有猫鼬设置,以创建一个适当的后端,但现在有虚拟项目,以解决这个问题,然后再继续。服务器从未工作过,但我有一个类似的项目确实工作过。
我怀疑我没有理解路由器。正确地使用/ get /post,但是我尝试过阅读文档,只会变得更加混乱。
发布于 2022-07-27 22:24:44
您所有的代码实际上都是100%好的,您只是不正确地应用了bodyParser.json中间件功能。bodyParser.json函数本身不是一个中间件函数,它是一个接受options对象的函数,然后当它被调用时返回一个中间件函数。
因此,要修复代码,只需添加()来调用函数:
const express = require('express');
const bodyParser = require('body-parser');
const routes = require('./items-routes');
const server = express();
server.use(bodyParser.json()); // <- Call the bodyParser.json() function
server.use('/api/items', routes);
const port = 5000;
try {
  server.listen(port);
  console.log(`Listening on port ${port}`);
} catch (error) {
  console.log(error.message);
}它之所以永远挂起,是因为Express在向前移动之前一直在等待bodyParser.json函数调用next();然而,它从来没有这样做,所以它只是挂起。
旁注:
顺便说一下,如果您使用的是最新版本的Express,则不再需要body-parser模块。您的代码可以更改为:
server.use(express.json());如果没有额外的依赖,它也会同样工作。
https://stackoverflow.com/questions/73145074
复制相似问题