how can I repeat something in Express?

Viewed 374

I am learning node and Express, I want to repeat a word in Express Example

user visits ....../repeat/hello/5 I want "hello" to print 5 times on the browser page,

If they do /repeat/hello/3 I want "hello" printed 3 times. How can I do this? Do I use a for loop if so can I nest the for loop?

Here is my code

var express = require("express");
var app = express();
//const repeating = require("repeating");

app.get("/", function(req,res){
    res.send("Hi there, welcome to my Assignment!");
});

//pig

app.get("/speak/pig", function(req,res){
    res.send("The pig says Oink");
});

//cow

app.get("/speak/cow", function(req,res){
    res.send("The cow says Moo");
});

//dog

app.get("/speak/dog", function(req,res){
    res.send("The dog says Woof, Woof!");
});

app.get("/repeat/hello/:3", function(req,res

    res.send("hello, hello, hello");
});

app.get("/repeat/blah/:2", function(req,res){
    res.send("blah, blah");
});

app.get("*", function(req,res){

    res.send("Sorry, page not found... What are you doing with your life?")

});

app.listen(3000, function(){
    console.log('Server listening on Port 3000');
});
1 Answers

You can use req.params to access the URL params. You can also parametrize the word which you want to repeat:

app.get("/repeat/:word/:times", function(req,res){

    const { word, times } = req.params;

    res.send(word.repeat(times));
});

This way, you can get rid of /repeat/hello and /repeat/blah endpoints and have only one generic endpoint which handles all words and all numbers

If you want to have a separator, then you can create a temporary array and join it, like this:

const result = (new Array(+times)).fill(word).join(',');
res.send(result);
Related