首页 > 解决方案 > node.js 中 req.param 中的未知值

问题描述

我正在学习node.js,因此尝试构建一个显示当前新闻的简单网络应用程序。API我正在使用的为新闻提供了几个类别。

所以我创建了一个将类别作为参数的路线。我的routes/index.js

const router = require('express').Router();
const renderHome = require('../controllers/newsController');
const quotesCookie = require('./../middleware/quotesCookie');

router.get('/', quotesCookie, renderHome);
router.get('/:category', quotesCookie, renderHome);


module.exports = router;

我的controllers/newsController.js样子是这样的:

const newsService = require('./../services/newsService');

const renderHome = async ( req, res ) => {
  const category = req.params.category;
  console.log(req.params);

  const quote = res.quoteOfTheDay;

  const { status, msg } = await newsService.topHeadlines(category);

  res.render('home', {
    title: 'News2Go',
    author: quote.author,
    quote: quote.quote,
    articles: msg.articles
  });
};


module.exports = renderHome;

例如,当我在控制器中调用http://localhost:3000/entertainmentconsole.log,会将其打印到控制台:

{ category: 'entertainment' }
{ category: 'sw.js' }

我完全不知道sw.js它来自哪里......它出现在真实类别之后几毫秒,并确保它topHeadlines被调用了两次。

有人知道这是什么吗?我错过了什么?

标签: javascriptnode.jsparameters

解决方案


显然,您的网页中有一个名为sw.js. 因此,浏览器将使用 URL 请求该请求,http://localhost:3000/sw.js而您的:category路由将处理该请求并记录sw.js.

请记住,您网站上使用的所有资源都将由浏览器请求,并且将被您的 Express 服务器视为传入请求。不仅是顶级页面,还有页面使用的所有脚本、图像、字体、CSS 文件等。

像这样定义一个开放的顶级路由处理程序通常不是一个好主意:

router.get('/:category', ...)

因为这将获取所有顶级 URL,而不会为您网站的其余部分留下任何内容。使用这样的结构可能更有意义:

router.get('/category/:category', ...)

URL 为http://localhost:3000/category/entertainment. 然后,您可以更清楚地将实际类别请求与站点中的所有其他请求区分开来。要么,要么您必须将您网站上使用的所有其他 URL 移动到此之前的路由和/或使用其页面中的子目录,例如:

 http://localhost:3000/scripts/sw.js
 http://localhost:3000/styles/main.css

推荐阅读