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');
});
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
I'd like to start by letting everyone know that I am new to coding in node. With that out of the way let me explain what I am trying to build, I'm trying to build a site where a user can use a button on the main page to visit a page that has a randomized route, but only once. So once you have visited that route, you need to click on the link again to see the same contents but on a different route. That will ensure users have to click on the button and can't just cheat the system by entering the same link over and over. So in basic terms I need the app to:
-Temporarily serve a HTML form (to get information) on a randomized route/link (could be for a single request or for some time, say 10 minutes)
-Delete that route/link
-Start over
Here is the code I have so far:
const express = require('express')
const app = new express();
const fs = require('fs');
var link = Math.floor(Math.random() * (1000 - 0) + 0)
var changingroute = function (req, res, next) {
app.get('/' + link, function(req, res){
res.sendFile(__dirname + '/public/download.html');
});
setTimeout(endroute, 1000)
function endroute() {
app.delete('/' + link)
console.log('Route Closed: LocalHost:8080/', link);
}
link = Math.floor(Math.random() * (1000 - 0) + 0)
console.log('Route Opened: localhost:8080/',link);
next()
}
//app.use(changingroute);
const port = process.env.PORT || 8080;
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.renderFile(__dirname + '/public/index.html');
});
app.get('/' + link, function(req, res){
res.sendFile(__dirname + '/public/download.html', '/public/download.html', function(err, res) {
if (!err) {
res.setHeader('Location', pathname + '/');
}
});
});
app.listen(port, function() {
console.log('app running');
console.log(`Route Opened: http://localhost:8080/${link}`);
});
Explanation:
The current code doesn't do what I would like it to. As you can probably tell changingroute isn't used, the app.use is commented. What it did do was create new routes every time a request was made but it wouldn't close the route afterwards. Where I was last with this code was testing out something someone else did on SO but it kind of differed from what I am trying to do : Serving Temporary Files with NodeJs. With their code you can put up files to download but only once but that doesn't really translate to routes and pages as I understand. I get errors like "cannot replace header" if I try and change the page it displays, or if I try and close the route. I haven't seen any tutorials online that show how to make temporary routes, or maybe I haven't used the right keywords. If you have any advice on where I should look or what I should try please let me know. I would really appreciate it!
I'm on the Node.js repl, I created a new project folder and initialized the NPM, then I installed the Express package and wrote the following code into the js file:
const express = require('express');
const app = express();
app.listen(5000, function(){
console.log("server started on port 5000");
})
app.get("/", function(req, res){
res.send("Hi There! Welcome!")
})
app.get("/speak/:animalName", function(req,res){
var animalName = req.params.animalName;
var verso = "verso";
if (animalName = "pig"){
verso = "oink"
} else if (animalName = "dog"){
verso = "bau"
} else if (animalName = "cat"){
verso = "Miao"
}
console.log(req.params);
res.send("THE " + animalName + " says " + verso);
})
app.get("*", function (req, res){
res.send("Sorry, the page cannot be found")
})
When I open the js file with Nodemon the server starts correctly and when I type a specific pattern in the URL field the console.log returns me the req.params correctly (in the example below: for I typed "cat" the console returned { animalName: 'cat' }
Nonetheless, the response in the browser is not the correct one:
You're using a single = in your conditions. This always assigns the variable, instead of testing for equality. Use == or ===.
I want setting like this
localhost:3000/some-special-days-one--parameterThat
How Can I setting and getting in router like this url and parameter in node js express framework?
I think that this is what you are trying to do:
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
app.get('/firstParameter/:id', function (req, res) {
res.send('my id is: ' + req.params.id);//this is the id
});
app.listen(3000);
In this example, if the user went to the URL localhost:3000/firstParameter/someId, The page would show "my id is: someId".
Hope this helps!
PS
If you do not want to have the / you can simply do:
app.get('/:id', function (req, res) {
var id = req.params.id;
idArr = id.split("firstParameter--");
id = idArr[1];
res.send('my id is: ' + id); //this is the id
});
Then, like above, just go to http://localhost:3000/firstParameter--helloand it will print out "my id is: hello"
I have been creating a website with Mean stack and I stuck at some point. I have a mongo db database and I am currently getting each file from database (to show them on Main page) with my Rest Api which is build with Express.
Server.js
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('mongodb://username...', ['myApp']);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.get('/myApp', function (req, res) {
db.myApp.find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.get('/myApp/:id', function (req, res) {
var id = req.params.id;
console.log(id);
db.myApp.findOne({_id: mongojs.ObjectId(id)}, function (err, doc) {
res.json(doc);
})
});
app.listen(3001);
console.log('Server running on port 3001');
There is 2 get method and I can understand that because they have different parameters. So when I call them from controllers, there is no problem because if I provide id, it will call the second get method. But for example I want to use something like this in my website;
app.get('/myApp', function (req, res) {
db.myApp.find({}).limit(2).skip(0, function(err, docs) {
console.log(docs);
res.json(docs);
});
});
This get method have no parameter like the first get method in server.js but they do different jobs. This is limiting my search with 2 file. How can I use different get methods like this in my Mean Stack application?
This is my code for calling get method from my main controller. How can I make sure to call specific get method? Thanks..
$http.get('/myApp').success(function(response) { .. });
What you want is not possible. Somehow you need to distinguish between your 2 intentions, either by giving the endpoints different names (like you already suggest in your comment) or by providing for example a query parameter so you could do a call like:
$http.get('/myApp?limit=2').success(function(response) { .. });
When limit is omitted, you could return all results.
Something like:
app.get('/myApp', function (req, res) {
var limit = req.query.limit;
if (limit === undefined) {
// Return everything
} else {
// make sure limit is some valid number
// ... and do a mongo query limited to this number
}
});
I really hope to find some answers here as i tried everything by now.
Background:
Overtime we deploy code to web server, we need to do a cache warm up, i.e. access the site and make sure it loads. First load is always the slowest since IIS require to do some manipulations with a new code and cache it.
Task:
Create a page which will a checkbox and a button. Once button is pressed, array of links sent to server. Server visits each link and provides a feedback on time it took to load each page to the user.
Solution:
I am using node JS & express JS on server side. So far i manage to POST array to the server with links, but since i have limited experience with node JS, i can not figure out server side code to work.
Here is a code i got so far (it is bits and pieces, but it gives an idea of my progress). Any help will be greatly appreciated!!!
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var parseUrlencoded = bodyParser.urlencoded({ extended: false});
var http = require("http");
function siteToPrime(url){
http.get(url, function (http_res) {
// initialize the container for our data
var data = "";
// this event fires many times, each time collecting another piece of the response
http_res.on("data", function (chunk) {
// append this chunk to our growing `data` var
data += chunk;
});
// this event fires *one* time, after all the `data` events/chunks have been gathered
http_res.on("end", function () {
// you can use res.send instead of console.log to output via express
console.log(data);
});
});
};
//Tells express where to look for static content
app.use(express.static('public'));
app.post('/', parseUrlencoded, function(request, response){
var newBlock = request.body;
console.log(Object.keys(newBlock).length);
var key = Object.keys(newBlock)[0];
console.log(newBlock[key]);
siteToPrime("www.google.com");
response.status(201);
});
app.listen(3000, function(){
console.log("Server listening on port 3000...");
});
Assuming that you have access to the array in the post route:
var express = require("express"),
request = require("request"),
app = express();
var start = new Date();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: false}));
function siteToPrime(req, res, urls) {
urls.forEach(function(url)) {
request(url, function(error, res, body) {
if (!error && res.statusCode == 200) {
console.log(url +' : ' + body);
console.log('Request took: ', new Date() - start, 'ms');
}
});
}
res.redirect('/');
};
app.post('/', function(req, res){
var urls = req.body.urls // Array os urls.
siteToPrime(req, res, urls);
});
app.listen(3000, function(){
console.log("Server listening on port 3000...");
});