How to set set url parameter with special character in node js? - javascript

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"

Related

How to let input appear in path without ?search in NODEjs?

Hi I am doing a NodeJS practice and I would like to let the input appear on the url as (website).com/results/NameOfCountry, where NameOfCountry is a variable containing the input by the user.
I don't know how to do it after trying path.dirname(), which I don't think is correct.
Everytime I key in the country name, it would show a link ending like /results?searchCountry=America and I'd like to get rid of the ?searchCountry because the correct path has an ending like /results/America
Could anyone help me with this? Thanks in advance.
Here's the Code
NodeJS:
var express = require("express");
var haste = express();
var bp = require("body-parser");
var request = require("request");
var mime=require('mime-types');
haste.set("view engine", "ejs");
haste.get("/", function(req, res){
res.render("search");
})
haste.get("/results", function(req, res){
var apple = "https://api.covid19api.com/total/country/" + query;
var query = req.you.value;
request(apple, function(error, response, require){
if(!error && response.statusCode == 200){
var data = JSON.parse();
res.render("info", {data:data});
}
})
})
haste.listen(process.env.PORT || 3000, process.env.IP, function(){
console.log("Server has started!");
});
On EJS, here's how the input form is:
<h1>
Find Cases By Country:
</h1>
<form action="/results" method="GET">
<input type="text" placeholder="enter country" class="you">
<input type="submit">
</form>
If you are referring to route params, then it is something like
haste.get("/results/:NameOfCountry", function(req, res){ ....}
where route/path params are prepended with a :. Then you have access to :NameOfCounty to use as needed via req.params
If I understand correctly you want to use a custom path for each search result instead of queries. You can achieve this with parameters in express.
A basic get route would look like this:
app.get("/results/:search", function(req, res){
var parameter = req.params.search;
//send your custom response here
}
The parameter variable contains what is after /results/ as a string

how can I repeat something in Express?

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);

Why is the server response incorrect when the request is read correctly?

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 ===.

Body parser not letting localhost load NODE

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
//PROBLEM LINE
**app.use(parser.json);**
///////////////
var todos = [];
var nextTodoItem = 1;
app.use(bodyParser.json);
app.get('/', function(req, res){
//console.log("ToDo Root");
res.send("ToDo Root");
});
//GET REQUEST TO GET ALL TODO ITEMS
// GET /todos
app.get('/todos', function (req, res) {
// Need to send back the array of todos
res.json(todos); //array is converted to JSON.
}
);
//GET REQUEST TO GET SOME SPECIFIC TODO
//GET todos/:id
//Express uses : (colon) to parse data.
app.get('/todos/:id', function (req, res) {
var todoID = parseInt(req.params.id, 10);
var todoObjectWithID = -1;
todos.forEach(function (todo) {
if(todo.id == todoID){
todoObjectWithID = todos[todoID - 1];
}
});
if(todoObjectWithID == -1){
res.status(404).send();
} else {
res.json(todoObjectWithID); //Send the JSON of the specific todo with id requested.
}
console.log('Asing for todo with id of ' + req.params.id);
});
//Create a POST request to create new TODO Items.
//POST /todos
app.post('/todos', function(req, res){
var body = req.body;
console.log("description");
res.json(body);
});
//Server basic start up (port and log)
app.listen(3000, function () {
console.log("Server up and running");
});
I run the server with bash (Mac OS) but I go to http://localhost:3000 nothing loads, but when I remove the app.use(bodyParser) it loads properly.
What is the problem in the body-parser?
This problem only occurs when I have that line, otherwise, the server runs up perfectly fine. I need that parser though, so what is my option?
Change that line to app.use(bodyParser.json());

Node orm2: orm.connect callback is not called

I would like to try out node orm2, with sqlite. I tried the example code, and changed mysql to sqlite. It looks like this:
var orm = require("orm");
orm.connect('sqlite://D:/orm_test/database.db', function (err, db) {
// ...
});
I don't get any error, or warning. Just nothing happens. The callback is not called at all.
It does not work, even if I create database.db before
According to the documentation the callback is only called when the connection is done successfully (or unsuccessfully)...
So if your path is incorrect (for any reason, and your connection is NOT explicitly unsuccessfull), maybe there is no callback ?
You can avoid callback if you listen for the connect event directly as this :
var orm = require('orm');
var db = orm.connect('sqlite://D:/orm_test/database.db');
db.on('connect', function(err) {
if (err) return console.error('Connection error: ' + err);
// doSomething()...
});
The connection URL is like :
driver://username:password#hostname/database?option=value
You can use the debug option to prints queries into the console, maybe there will be more informations ?
EDIT :
Well, I just tried to use it and did that :
// REQUIRES
var express = require('express');
var app = express();
var orm = require("orm");
var sqlite3 = require('sqlite3');
// SERVER CONFIGURATION
var port = 5050;
// APP CONFIGURATION
app.use(express.static('public'));
app.use('/static', express.static(__dirname + '/public'));
app.set('views', __dirname + '/views');
// ROUTES
app.get('/', function(req, res){
orm.connect('sqlite://C:/Users/Me/Documents/Projects/test/database.db', function(err, db){
console.log('connected to this db : ' + JSON.stringify(db));
});
});
app.listen(port, function(){
console.info('Server successfully started, listening on port ' + port);
});
And it works... JSON.stringify shows what is the content of DB Object in the console.
Does your code looks like this ?

Categories