程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Express JS - 在服务器中添加一个路由来处理 POST 请求大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决Express JS - 在服务器中添加一个路由来处理 POST 请求?

开发过程中遇到Express JS - 在服务器中添加一个路由来处理 POST 请求的问题如何解决?下面主要结合日常开发的经验,给出你关于Express JS - 在服务器中添加一个路由来处理 POST 请求的解决方法建议,希望对你解决Express JS - 在服务器中添加一个路由来处理 POST 请求有所启发或帮助;

我是 JavaScript 新手,我正在尝试学习 express 并创建一个应用程序,该应用程序将允许用户创建新食谱、浏览现有食谱和查看食谱。

我通过在 cmd 栏中输入 recipeserver.Js 然后在我的 Google Chrome 上的地址栏中输入 localhost:3000 来运行我的服务器。到目前为止,它加载了 index.HTML 主页,然后,我可以单击标题为“创建食谱”的链接,该链接将我引导至如下所示的 create.HTML 页面:

create.html page

最初,服务器上只有三个配方,它们包含在我在下面包含的 recipeserver.Js 代码中的数据库对象中。 create.HTML 页面允许用户输入配方信息。当单击 Save Recipe 按钮时,addrecipe.Js 文件应该使用对资源 /recipes

的 POST 请求将配方数据发送到服务器

在服务器代码中,所有配方都将存储在一个名为数据库的对象中。此对象的键将是唯一 ID,值将是与这些 ID 关联的配方。我被困在一个任务上,我应该在服务器代码中添加一个路由来处理对 /recipes 资源的 POST 请求。此路由的处理程序应该:

@H_675_12@
  • 提取包含在 POST 请求正文中的配方对象
  • 为新配方生成一个唯一 ID(等等,每次添加配方时都会增加一个基本整数。)
  • 向配方对象添加一个新条目,键是唯一 ID,值是配方对象。
  • 通过向我的服务器添加一些配方来测试我的代码时,我应该能够只记录配方对象的内容以查看它是否存储了正确的数据,如下图所示(这张图片不是我的):

    load recipe in cmd

    所以如我屏幕的第一张图片所示,我填写了我想在 create.HTML 中添加的食谱的内容。然而,当我点击“保存食谱”按钮时,我没有将食谱的内容加载到我的 cmd 窗口中,而是出现错误:

    TypeError: C:\Downloads\recipeApplication\vIEws\recipes.pug:8
        6|     div#main
        7|         h1 List of Recipes:
      > 8|         each recipe in recipes
        9|             a(href="/recipes/" + recipe.ID) #{recipe.namE}
        10|             br
        11|
    
    CAnnot read property 'length' of undefined
    

    我对如何在服务器代码中路由以处理对 /recipes 资源的 POST 请求感到有些困惑。我创建了一个名为 loadRecipes() 的函数,我正在尝试在其中执行所有这些操作。我尝试创建一个新的 ID 并将其增加 1,就像任务建议的那样。我在提取 POST 请求正文中包含的配方对象时遇到问题。我尝试了这个并最终将其注释掉,因为它产生了相同的错误。我只是想让 Save Recipe 按钮起作用,以便添加的食谱在 cmd 栏中打印其内容,就像第二张图片一样,但我真的迷失了,并且被出现的信息量淹没了我尝试寻找解决方案,并希望得到一些帮助以使其发挥作用。

    这是我所有的代码,以防有人想运行它,但我相信我的问题只是出在 recipeserver.Js 文件中。单击 Save Recipe 按钮后,addrecipe.Js 文件使用对资源 /recipes 的 POST 请求将配方数据发送到服务器。

    recipeserver.Js:

    const express = require('express');
    const fs = require("fs");
    const shortID = require("short-ID");
    const session = require('express-session');
    const app = express();
    const pug = require("pug");
    const port = 3000;
    
    
    let database = {
        "0":{
            "ingredIEnts":
            [
                {"name":"Crab","unit":"Tsp","amount":3},{"name":"Peas","unit":"Cup","amount":12},{"name":"Basil","unit":"Tbsp","amount":10},{"name":"Cumin","unit":"liter",{"name":"Salt","amount":1}
            ],"name":"Boiled Crab with Peas","preptime":"13","cooktime":"78","description":"A boring recipe using Crab and Peas","ID":"0"
        },"1":{
            "ingredIEnts":
            [
                {"name":"Peanuts",{"name":"Artichoke","amount":11},{"name":"Sage","unit":"Grams","amount":13},{"name":"Pepper","name":"Boiled Peanuts with Artichoke","preptime":"73","cooktime":"74","description":"A exciTing recipe using Peanuts and Artichoke","ID":"1"
        },"2":{
            "ingredIEnts":
            [
                {"name":"Lobster","amount":14},{"name":"Brussel Sprouts",{"name":"Thyme","amount":11}
            ],"name":"Spicy Lobster with Brussel Sprouts","preptime":"86","cooktime":"19","description":"A tasty recipe using Lobster and Brussel Sprouts","ID":"2"
        }
    }
    
    
    let recipes = {};
    
    for (let recipe in databasE) {
      recipes[recipe.ID] = recipe;
    };
    
    app.set("vIEw ENGIne","pug");
    app.use(express.static("public"));
    app.use(express.Json());
    app.use(expresS.Urlencoded({extended: truE}));
    
    
    
    app.get("/addrecipe.Js",getAddRecipeJs);
    app.get("/recipes",loadRecipes);
    app.get("/recipe",loadRecipE);
    app.route("/recipes",loadRecipes);
    app.post("/recipes",loadRecipes);
    
    let ID = 1; 
    function loadRecipes(request,response,next){
        response.status(200).render("recipes.pug",{"session": request.session});
        /*
        console.log("request received!",request.body);
        const newID = shortID.generate();
        recipes[newID] = {
          ID: newID,type: "recipe",...request.body,};
        response.sendStatus(201);
        */
        ID++;
    }
    
    function loadRecipe(req,res,next){
        res.status(200).render("recipe.pug",{"session": req.session});
    }
    
    function getAddRecipeJs(req,next){
        fs.readfile("addrecipe.Js",function(err,data){
            if(err){
                res.statusCode = 500;
                res.end("Error reading file.");
                return;
            }
            res.status(200).send(data);
            return;
        });
    }
    
    app.Listen(port);
    console.log(`Server Listening at http://localhost:${port}`);
    

    index.HTML:

    <HTML>
    
        <head><title>Recipe App Home Page</title></head>
        
        <body>
            <h1>Welcome to the Recipe App</h1>
            <br>
            <a href="/create.HTML">Create a Recipe</a><br>
            <a href="/recipes">browse Recipes</a><br>       
        </body>
    </HTML>
    

    create.HTML:

    <HTML>
        <head><title>Create a Recipe</title></head>
        
        <body>
            <script src="/Js/addrecipe.Js"></script>
            
            <button type="button" onclick="genRandom()">Generate Random Recipe Data</button>
            <button type="button" onclick="submit()">Save Recipe</button>
            <br><br>
            
            Recipe name: <input type="textBox" ID="recip@R_772_8371@" size="50"><br>
            
            Prep Time: <input type="textBox" ID="preptime" size="50"><br>
            
            Cook Time: <input type="textBox" ID="cooktime" size="50"><br>
            
            Description: <textarea rows="5" cols="50" ID="description"></textarea><br><br>
            
            Add ingredIEnts:<br>
            Unit: <SELEct ID="unit">
            <option value="Tsp">Teaspoon</option>
            <option value="Tbsp">Tbsp</option>
            <option value="Cup">Cup</option>
            <option value="liter">liter</option>
            <option value="Gram">Gram</option>
            </SELEct><br>
            
            amount: <input type="textBox" ID="amount"><br>
            
            IngredIEnt: <input type="textBox" ID="ingredIEnt"><br>
            
            <button type="button" ID="add" onclick="addIngredIEnt()">Add IngredIEnt</button>
            <br><br>
            <div ID="ingredIEnts">
            
            </div><br>
            <button type="button" ID="submit" onclick="submit()">Save Recipe</button>
        </body>
    </HTML>
    

    addrecipe.Js:

    let descriptors = ["Sweet","Spicy","BBQ","Braised","Deconstructed","broiled","Boiled","Flambeed","Raw","Smoked","ButterflIEd","Cured","Grilled","Poached"];
    let proteins = ["Chicken","Beef","Lobster","Shrimp","Crab","Turkey","Duck","Tofu","Chickpeas","Lentils","Peanuts","Kangaroo","Human","Goose","Fish","Pork","Eggs","Deer"];
    let accompany = ["broccoli","Carrots","Peas","Potato","Kale","Banana","Artichoke","Asparagus","Beans","broccoli","Brussel Sprouts","Celery","Melon","Mushrooms","Pumpkin"];
    let spices = ["Salt","Pepper","Basil","Thyme","Sage","Cumin"];
    let mealDescriptors = ["tasty","mediocre","very good","boring","exciTing","delicIoUs","easy","rIDiculously complex"];
    let units = ["Tbsp","Tsp","Cup","liter","Grams"]
    
    let recipe = {ingredIEnts: []};
    
    function addIngredIEnt(){
        let name = document.getElementByID("ingredIEnt").value;
        let amount = document.getElementByID("amount").value;
        let unit = document.getElementByID("unit").value;
        let ingredIEnt = {name,amount,unit};
        recipe.ingredIEnts.push(ingredIEnt);
        updateIngredIEnts();
    }
    
    function updateIngredIEnts(){
        let INNERHTML = "";
        recipe.ingredIEnts.forEach(ingredIEnt => {
            INNERHTML += ingredIEnt.amount + " " + ingredIEnt.unit + " " + ingredIEnt.name + "<br>";
        });
        document.getElementByID("ingredIEnts").INNERHTML = INNERHTML;
    }
    
    function submit(){
        recipe.name = document.getElementByID("recip@R_772_8371@").value;
        recipe.preptime = document.getElementByID("preptime").value;
        recipe.cooktime = document.getElementByID("cooktime").value;
        recipe.description = document.getElementByID("description").value;
        
        let req = new XMLhttprequest();
        req.onreadystatechange = function() {
            if(this.readyState==4 && this.status==200){
                alert("recipe saved");
            }
        }
        
        //Send a POST request to the server containing the recipe data
        req.open("POST",`/recipes`);
        req.setrequestheader("Content-Type","application/Json");
        req.send(JsON.Stringify(recipE));
    }
    

    recipes.pug:

    HTML
        head
            title Recipes
    body
        a(href="/create.HTML") add a recipe
        div#main
            h1 List of Recipes:
            each recipe in recipes
                a(href="/recipes/" + recipe.ID) #{recipe.namE}
                br
    

    recipe.pug:

    HTML
        head
            title #{recipe.namE}
    body
    
        div#main
            h1 #{recipe.namE}
            br
    

    解决方法

    首先,感谢您努力详细解释您的问题。一个建议是,您可以共享存储库而不是代码片段(因为它很长,而且文件夹的结构确实会影响我们如何让它运行)。

    尽管如此,您得到的错误是由于 recipes 中的 recipes.pug 实际上是 undefined

    index.js

    function loadRecipes(request,response,next) {
          response
            .status(200)
            // Here,you only pass `session` object to the template ENGIne
            // So template ENGIne does not know about `recipes`
            // So `recipes` is undefined,and you can't loop it
            .render('recipes.pug',{ session: request.session});
         
          id++;
        }
    

    recipes.pug

    html
        head
            title Recipes
    body
        a(href="/create.html") add a recipe
        div#main
            h1 List of Recipes:
            // You're having issue here,since `recipes` is not passed to the template 
            // ENGIne,it will throw an error
            each recipe in recipes
                a(href="/recipes/" + recipe.id) #{recipe.namE}
                br
    

    使用此更新您的 index.js

    function loadRecipes(request,next) {
          response
            .status(200)
            .render('recipes.pug',{ session: request.session,recipes: database });
         
          id++;
        }
    

    现在,您应该能够查看 /recipes 页面并继续处理该项目。 我注意到您的代码中有相当多的错误。

    app.get('/addrecipe.js',getAddRecipeJS);
    app.get('/recipes',loadRecipes);
    app.get('/recipe',loadRecipE);
    app.route('/recipes',loadRecipes);
    app.post('/recipes',loadRecipes);
    

    根据此路由列表,您不应使用相同的 function 来处理 POSTGET/recipes 请求。

    GET 可用于检索 recipes 的列表 POST 应该用于处理提交的数据,并将其保存到 index.js 中的 database 变量

    我会给你一个简单的方法(你也应该真正探索自己)

    app.post('/recipes',saveRecipes);
    
    function saveRecipes(req,res,next) {
      // Data submitted from your page is available in `req.body`
      console.log(req.body);
      // I'm trying to get a new `key` for the database
      // This is because you're using number as `key` for each recipe
      // Can skip this and use some random uuid as well
      const dbLength = Object.keys(databasE).length;
      // Add this to the database variable,and you're DONE!
      database.dbLength = req.body;
      res.send('ok');
    }
    

    大佬总结

    以上是大佬教程为你收集整理的Express JS - 在服务器中添加一个路由来处理 POST 请求全部内容,希望文章能够帮你解决Express JS - 在服务器中添加一个路由来处理 POST 请求所遇到的程序开发问题。

    如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

    本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
    如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
    标签:-请求