简体   繁体   English

无法获取 /posts/whatever 。 看起来 req.params 不起作用

[英]Cannot GET /posts/whatever . It looks like req.params is not working

I am newbie at this, so sorry for some silly mistakes.我是新手,对于一些愚蠢的错误很抱歉。 Happy to learn.乐于学习。 Whenever I use URL : localhost:3000/posts/whatever I get a cannot GET error.每当我使用 URL 时: localhost:3000/posts/whatever 我得到一个无法获取错误。 Before you ask, yes that is after I put content in posts page.在你问之前,是的,那是在我将内容放入帖子页面之后。 It looks like there is some problem with req .看起来req有问题。

This is my code:这是我的代码:

//jshint esversion:6

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const _ =require("loadash");

const homeStartingContent = "Lacus vel facilisis volutpat est velit egestas dui id ornare. Semper auctor neque vitae tempus quam. Sit amet cursus sit amet dictum sit amet justo. Viverra tellus in hac habitasse. Imperdiet proin fermentum leo vel orci porta. Donec ultrices tincidunt arcu non sodales neque sodales ut. Mattis molestie a iaculis at erat pellentesque adipiscing. Magnis dis parturient montes nascetur ridiculus mus mauris vitae ultricies. Adipiscing elit ut aliquam purus sit amet luctus venenatis lectus. Ultrices vitae auctor eu augue ut lectus arcu bibendum at. Odio euismod lacinia at quis risus sed vulputate odio ut. Cursus mattis molestie a iaculis at erat pellentesque adipiscing.";
const aboutContent = "Hac habitasse platea dictumst vestibulum rhoncus est pellentesque. Dictumst vestibulum rhoncus est pellentesque elit ullamcorper. Non diam phasellus vestibulum lorem sed. Platea dictumst quisque sagittis purus sit. Egestas sed sed risus pretium quam vulputate dignissim suspendisse. Mauris in aliquam sem fringilla. Semper risus in hendrerit gravida rutrum quisque non tellus orci. Amet massa vitae tortor condimentum lacinia quis vel eros. Enim ut tellus elementum sagittis vitae. Mauris ultrices eros in cursus turpis massa tincidunt dui.";
const contactContent = "Scelerisque eleifend donec pretium vulputate sapien. Rhoncus urna neque viverra justo nec ultrices. Arcu dui vivamus arcu felis bibendum. Consectetur adipiscing elit duis tristique. Risus viverra adipiscing at in tellus integer feugiat. Sapien nec sagittis aliquam malesuada bibendum arcu vitae. Consequat interdum varius sit amet mattis. Iaculis nunc sed augue lacus. Interdum posuere lorem ipsum dolor sit amet consectetur adipiscing elit. Pulvinar elementum integer enim neque. Ultrices gravida dictum fusce ut placerat orci nulla. Mauris in aliquam sem fringilla ut morbi tincidunt. Tortor posuere ac ut consequat semper viverra nam libero.";

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

let posts = [];

app.get("/", function(req,res){
  res.render("home", {
    startingContent: homeStartingContent,
    posts:posts
  });
});

app.get("/contact",function(req,res){
  res.render("contact",{contactContent: contactContent});
});

app.get("/about",function(req,res){
  res.render("about",{aboutContent: aboutContent});
});

app.get("/compose",function(req,res){
  res.render("compose");
});

app.post("/compose", function(req, res){
  const post = {
    title: req.body.postTitle,
    content: req.body.postBody
  };

  posts.push(post);

  res.redirect("/");

});

app.get("/posts/:postName", function(req, res){
  const requestedTitle = _.lowerCase(req.params.postName);
  posts.forEach(function(post){
      const storedTitle = _.lowerCase(post.title);

      if(storedTitle === requestedTitle){
        res.render("post",{
            title:post.title,
            content:post.content,
        });
      }
  });
});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

In your code you'll have to correct lodash from loadash in the require section.在您的代码中,您必须在 require 部分从loadash中更正lodash

Also I do believe it's your middelware that's a problem.我也相信这是你的中间件有问题。

I added a bunch of log lines to see how your code is manipulated.我添加了一堆日志行来查看您的代码是如何操作的。

This is the compose function:这是撰写功能:

app.post("/compose", function(req, res){
  console.log('(BODY) compose variables: ', req.body.postTitle, req.body.postBody)
  console.log('(PARAMS) compose variables: ', req.params.postTitle, req.params.postBody)
  console.log('(QUERY) compose variables: ', req.query.postTitle, req.query.postBody)
  const post = {
    title: req.body.postTitle,
    content: req.body.postBody
  };
  console.log('compose variables as object', post)
  posts.push(post);
  console.log('object pushed to array', posts)
  res.redirect("/");

});

And this is the GET /posts/:postTitle function.这就是GET /posts/:postTitle函数。

app.get("/posts/:postName", function(req, res){
  const requestedTitle = _.lowerCase(req.params.postName);
  console.log('requestedTitle: ', requestedTitle)
  console.log('Array to loop: ', posts)
  posts.forEach(function(post){
      console.log('current looped object: ', post)
      const storedTitle = _.lowerCase(post.title);
      console.log('looped title: ', post.title)
      console.log('storedtitle: ', storedTitle)

      if(storedTitle === requestedTitle){
        res.render("post",{
            title:post.title,
            content:post.content,
        });
      }
  });
});

These log lines showed me that everything works just fine if I compose the right POST request in Postman.这些日志行告诉我,如果我在 Postman 中编写正确的POST请求,一切都会正常工作。

POST http://localhost:3000/compose Body: x-www-form-urlencoded, postTitle: test, postBody: testbody POST http://localhost:3000/compose Body: x-www-form-urlencoded, postTitle: test, postBody: testbody

If you're sending your information in the POST request other than urlencoded you'll have to load the bodyParser middelware that matches.如果您在POST请求中发送信息而不是 urlencoded,则必须加载匹配的 bodyParser 中间件。

If I send data as params (URL) or normal form data it populates the posts array with empty objects.如果我将数据作为参数(URL)或普通形式数据发送,它会用空对象填充posts数组。


Log lines with correct Postman settings:具有正确 Postman 设置的日志行:
POST /compose

(BODY) compose variables: test (BODY) 组合变量:测试
(PARAMS) compose variables: undefined undefined (PARAMS) 组合变量: undefined undefined
(QUERY) compose variables: undefined undefined (QUERY) 组合变量: undefined undefined
compose variables as object { title: 'test', content: '' }将变量组合为对象 { title: 'test', content: '' }
object pushed to array [ { title: 'test', content: '' } ]对象推送到数组 [ { title: 'test', content: '' } ]

GET /posts/test

requestedTitle: test请求标题:测试
Array to loop: [ { title: 'test', content: '' } ]要循环的数组:[ { title: 'test', content: '' } ]
current looped object: { title: 'test', content: '' }当前循环对象:{标题:'测试',内容:''}
looped title: test循环标题:测试
storedtitle: test存储标题:测试


Log lines with form-data POST /compose带有表单数据POST /compose日志行

(BODY) compose variables: undefined undefined (BODY) 组合变量: undefined undefined
(PARAMS) compose variables: undefined undefined (PARAMS) 组合变量: undefined undefined
(QUERY) compose variables: undefined undefined (QUERY) 组合变量: undefined undefined
compose variables as object { title: undefined, content: undefined }将变量组合为对象 { 标题:未定义,内容:未定义 }
object pushed to array [ { title: undefined, content: undefined } ]对象推送到数组 [ { 标题:未定义,内容:未定义 } ]

GET /posts/test

requestedTitle: test请求标题:测试
Array to loop: [ { title: undefined, content: undefined } ]要循环的数组:[ { 标题:未定义,内容:未定义 } ]
current looped object: { title: undefined, content: undefined }当前循环对象:{ 标题:未定义,内容:未定义}
looped title: undefined循环标题:未定义
storedtitle:存储标题:


And log lines with data as params (URL data)并以数据为参数的日志行(URL 数据)

POST /compose?postTitle=test&postBody=testbody

(BODY) compose variables: undefined undefined (BODY) 组合变量: undefined undefined
(PARAMS) compose variables: undefined undefined (PARAMS) 组合变量: undefined undefined
(QUERY) compose variables: test testbody (QUERY) 组合变量:test testbody
compose variables as object { title: undefined, content: undefined }将变量组合为对象 { 标题:未定义,内容:未定义 }
object pushed to array [ { title: undefined, content: undefined } ]对象推送到数组 [ { 标题:未定义,内容:未定义 } ]

GET /posts/test

requestedTitle: test请求标题:测试
Array to loop: [ { title: undefined, content: undefined } ]要循环的数组:[ { 标题:未定义,内容:未定义 } ]
current looped object: { title: undefined, content: undefined }当前循环对象:{ 标题:未定义,内容:未定义}
looped title: undefined循环标题:未定义
storedtitle:存储标题:


So you should find out what data comes into your application and make sure you have the correct middleware loaded.因此,您应该找出进入您的应用程序的数据,并确保加载了正确的中间件。

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

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