简体   繁体   English

Express Router:我的路由无法正常工作,页面无法加载

[英]Express Router: I'm having an issue getting my routes to work, the page doesn't load

I'm having an issue getting my backend to work.... honestly it's not even loading, I get the log that the server has started but entering in http://localhost:5000/api/items loads indefinitely.我在让我的后端工作时遇到问题......老实说,它甚至没有加载,我得到服务器已启动但输入 http://localhost:5000/api/items 的日志无限期加载。 I'm not sure what I'm doing wrong.我不确定我做错了什么。

This is my server.js这是我的 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);
}

Here is my items-routes.js这是我的 items-routes.js

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;

And finally my items-controller.js最后是我的 items-controller.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;

I initially had mongoose set-up to create a proper backend but now have dummy items in order to solve this issue before moving on.我最初有 mongoose 设置来创建一个适当的后端,但现在有虚拟项目以便在继续之前解决这个问题。 The server never worked but I have a similar project that did work.服务器从未工作过,但我有一个类似的项目确实有效。

I have a suspicion that I'm not understanding router.use/get/post properly but I've tried reading the documentation and only get more confused.我怀疑我没有正确理解 router.use/get/post 但我尝试阅读文档但只会变得更加困惑。

All of your code is actually 100% okay, you just applied the bodyParser.json middleware function incorrectly.您的所有代码实际上都是 100% 好的,您只是错误地应用了bodyParser.json中间件 function。 The bodyParser.json function is not a middleware function itself, it is a function that takes an options object, then when it's called it returns a middleware function. The bodyParser.json function is not a middleware function itself, it is a function that takes an options object, then when it's called it returns a middleware function.

So, to fix your code, you just need to add () to call the function:因此,要修复您的代码,您只需添加()来调用 function:

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

The reason it was hanging forever is because Express was waiting on the bodyParser.json function to call next() before moving forward;它永远挂起的原因是因为 Express 正在等待bodyParser.json function 在继续之前调用next() however, it never does that, so it just hangs.但是,它从不这样做,所以它只是挂起。

Side note:边注:

By the way, you don't need the body-parser module anymore if you're using the latest version of Express.顺便说一句,如果您使用的是最新版本的 Express,则不再需要body-parser模块。 Your code can be changed to this:您的代码可以更改为:

server.use(express.json());

And it'll work just the same just without the extra dependency.没有额外的依赖,它的工作原理是一样的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM