需要有关node.js npm(express)的解释?

时间:2018-08-02 11:33:00

标签: javascript node.js express

请为我解释这条线是如何工作的

app.get("/speak/:animal", function(req, res) {
    var sounds = {
        pig: "OINK",
        cow: "MOO",
        dog: "WOOF WOOF",
        cat: "I hate humans",
        goldfish: "..."
    };

    var animal = req.params.animal.toLowerCase();
    var sound = sounds[animal];
    res.send("The " + animal + " says '" + sound + "'");
});

这行也请

app.get("/repeat/:message/:times", function(req, res) {
    var message = req.params.message;
    var times = Number(req.params.times);
    var result = "";
    for(var i = 0; i < times; i++) {
        result += message + " ";
    }

    res.send(result);
});

1 个答案:

答案 0 :(得分:0)

第一个:

  // Listens to all the get requests on the url path /speak/anything 
  // :animal is a placeholder, anything you pass in the url will be be available in the url param animal.
     app.get("/speak/:animal", function(req, res){
          // JSON object with a key value pair.
           var sounds = {
           pig: "OINK",
           cow: "MOO",
           dog: "WOOF WOOF",
           cat: "I hate humans",
           goldfish: "..."
       };
           // Converts the request parameter 'anything' in the url to a lower case string.
           var animal = req.params.animal.toLowerCase();
           // Tries to find the sound in the sounds object since 'anything' is no key it wont find a suitable value for the sound.
           var sound = sounds[animal];
           // Responds to the request with the resolved sound.
           res.send("The " + animal + " says '" + sound + "'");

第二个

// Let us consider that the request /repeat/received/10
     app.get("/repeat/:message/:times", function(req, res){
      // the  /received in the url will be available to access under the req.param.messages
       var message = req.params.message;
       // message = received 
       // Converting the times string 10 passed in the url to a number
       var times = Number(req.params.times);
       var result = "";
       // loop will run from 0 to 9 and keep appending to the string result
       for(var i = 0; i < times; i++){
           result += message + " ";
       }
       // At the end of the for loop
       // result will contain = 'received received received' 7 more time ...
       // will send the response to the request.
       res.send(result);

    });