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
Related
I am unable to set the values of HTML form inputs on to my Node JS variable.
Below is my JS code where I am not able to set the values of variables "hostname" and "port" which will in turn concatenate to a new variable called url.
console.log(url) prints just mongodb://:. which suggests that my HTML form values are not being stored in my Node JS variables.
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var router = express.Router();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
const dbname = "admin";
var hostname ='';
var port2 ='';
app.post('/', function(req, res){
hostname = req.body.hostname;
port2 = req.body.port2;
});
var url ="mongodb://"+hostname+":"+port2;
Below is my html which is handling the form inputs
<form class="clr-form" action="/" method="POST">
<input type="text" name="hostname" placeholder="Enter Host Name" class="clr-input"> <br/>
<input type="text" name="port2" placeholder="Enter Port" class="clr-input"><br/>
<input type="submit" value="Submit" />
</form>
You don't need to redeclare the port2 again
var port2 ='';
app.post('/', function(req, res){
var hostname = req.body.hostname;
port2 = req.body.port2;
});
var url ="mongodb://"+hostname+":"+port2;
var hostname ='';
var port2 ='';
app.post('/', function(req, res){
hostname = req.body.hostname;
port2 = req.body.port2;
});
You should not declare variables inside the function again if you want to assign body values to your variables which one you will be using outside of scope.
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
}
});
So i have found an api for node https://github.com/schme16/node-mangafox
But i have no idea on how to use it
Lets say that i want to use this
mangaFox.getManga = function(callback){
$.get('http://mangafox.me/manga/',function(data){
var list = {};
data.find('.manga_list li a').each(function(index, d){
var b = $(d);
list[mangaFox.fixTitle(b.text())] = {id:b.attr('rel'), title:b.text()};
});
(callback||function(){})(list);
}, true);
}
What should i do to show the list in the '/' route
This i what i have so far
var express = require('express'),
path = require('path'),
mangaFox = require('node-mangafox');
var app = express();
app.get('/', function(req, res) {
});
app.listen(1337);
console.log('oke');
If some cloud help me understand how this works
app.get('/', function(req, res) {
function renderList(data) {
return Object.keys(data);
res.send(JSON.stringify(list));
}
var list = mangaFox.getManga(renderList);
});
This is the simplest thing I can come up with. You just get the object returned by the module, list its keys, and send back that stringified as your response. Try it out. You'll probably want to replace the renderList with some HTML templating.
I am using Node.js and express to make a web chat application. I have a question about routing.
My route is:
app.get("/", function( req, res ) {
res.sendfile( __dirname + "/index.html" );
});
And as far as I know it means all clients should go to http://www.example.com/index.html page to access the chat. ( maybe, not sure )
Is it possible to have a pattern URL like this:
app.get("/*", function( req, res ) {
res.sendfile( __dirname + "/*" );
});
so that any user can access to chat on any URL
In short: Something like facebook chat. which is accessible in all pages.
thanks in advance
Is it possible to have a pattern URL like this:
Yeah, Express supports exactly the route you listed. The documentation refers to it as an "unnamed wild-card."
// GET /foo -> (200) "foo"
// GET /baz/qux -> (200) "baz/qux"
app.get('/*', function (req, res) {
res.send(req.params[0]);
});
Though, for your example, Express/Connect includes a static() middleware for serving files by combining the URL path to a base directory:
app.use(express.static(__dirname));
Something like facebook chat. which is accessible in all pages.
This wouldn't necessarily have much of a relation to routing. Your application may need a route to gather a list of contacts or other persisted data, but the actual "chat" will be managed separately.
In general, it would depend on including common content in each page -- perhaps via a "layout" or "inheritance" if you're using views/templates -- to display the form for inputting message and an area to display chat history. Also, a fair amount of the "work" for the chat will have to be done client-side.
A quick example would be to serve the same file for multiple URLs:
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
app.get('/*', function (req, res) {
res.sendfile(__dirname + '/chat.html');
});
var chat = io
.of('/chat') // namespace
.on('connection', function (socket) {
socket.on('message', function (data) {
chat.emit('message', data);
});
});
server.listen(3000);
And, in that file:
<div id="chat-log"></div>
<form id="chat-send">
<input name="message">
<input type="submit" value="Send">
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var chatForm = document.getElementById('chat-send');
var chatLog = document.getElementById('chat-log');
var chatSocket = io.connect('/chat');
chatSocket.on('message', function (data) {
chatLog
.appendChild(document.createElement('div'))
.appendChild(document.createTextNode(data.text));
});
chatForm.onsubmit = function () {
chatSocket.emit('message', {
text: chatForm.message.value
});
chatForm.message.value = '';
chatForm.message.focus();
return false;
};
</script>
Then, from any address (GET /, GET /foo, GET /bar/baz/qux), you can access chat.
You're probably going to want to use a url param like this:
app.get("/:chatter",function(req,res){
console.log("the chatter is",req.param('chatter'));
res.sendfile( __dirname + "/index.html" );
...
});