I am trying to find a way to create a new page dynamically on Node.JS with Express when a user submits a form. Here is my idea, but it doesn't work:
var app = require('express')();
var server= require('http').createServer(app);
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
function Page(name){ //Create a page prototype
//Some variables and methods specific to the page
app.get('/'+name, function (req, res) {
res.render('index.ejs', {someVars: someVars});
});
}
//When a user submits a form, create a new page
app.post('/submit', urlencodedParser, function(req, res){
var nom = req.body.nom;
var newPage = new Page(nom);
res.redirect('http://myDomain/' + nom);
});
What is the best way to do it?
You could save names of created pages in database and set optional parameter in express:
//When a user submits a form, create a new page
app.post('/submit', urlencodedParser, function(req, res){
var nom = req.body.nom;
/* save nom to database */
res.redirect('http://myDomain/' + nom);
});
app.get('/:nom', function(req, res){
/* if nom exists in database -> return ejs template with vars */
/* else return 404 */
});
You should store it in database to prevent having pages that doesn't exist.
You need to add ejs as view engine and make sure you have created index.ejs and then add a get route for dynamic page as following
var app = require('express')();
var server= require('http').createServer(app);
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
// set the view engine to ejs
app.set('view engine', 'ejs');
app.get("/:pageName", function (req, res) {
var pageName = req.params.pageName;
res.render('index.ejs', {someVars: someVars});
});
//When a user submits a form, create a new page
app.post('/submit', urlencodedParser, function(req, res){
var nom = req.body.nom;
res.redirect('http://myDomain/' + nom);
});
I hope this will help you
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 have an array that is initialized when my user makes an input. I want that array to be passed to the nodeJS side of things rather than just stick around in the frontend. All the other variables that I am grabbing are named "net[object]" so I can grab them all in an array when necessary. The array I created only ever has one element being displayed in an input group at a time. If you need a better visual, go to "#nodes in hidden layer" for the neural net demo here: http://irisml.org/demos/
I am a complete noob when it comes to web development, so please be patient with me :)
//JS code creating array
numLayers.addEventListener('input', function(){
nodesArray.length = 0
num = numLayers.value;
nodes.innerHTML = '';
initialized = true;
for(var i = 1; i < num - 1; i++){
var node = document.createElement("option");
var textnode = document.createTextNode("Nodes in Hidden Layer " + i);
node.appendChild(textnode);
document.getElementById("nodes").appendChild(node);
nodesArray.push(1)
}
});
//Current NodeJS code
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.post('/', function(req, res){
console.log(req.body.net)
});
You can use "fetch" to send a post request to the backend.
//frontend
let nodesArray = [1,2,3];
let body = JSON.stringify({net:nodesArray});
fetch("/",
{method:"post",
body:body,
headers: {
'Content-Type': 'application/json'
}});
Your backend needs to listen on a port
//backend
var express = require('express');
var app = new express();
app.use(express.json())
app.listen(3000, console.error); //listen on port http://localhost:3000
app.use('/static', express.static(__dirname + '/static')); //OPTIONAL host static/index.html
app.post('/', function(req, res){
console.log(req.body.net, 'net');
res.send("RESPONSE");
});
This is a Node project, I'm getting a 'Cannot GET/' error when I try top open up localhost on port 8081. I'm almost certain it's just not reading in the HTML file correctly but I'm not sure.
var express = require('express');
var jsonfile = require('jsonfile');
var bodyParser = require('body-parser');
var app = express();
var file = 'C:/xampp/htdocs/codedb.json';
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('codeStore'));
app.use(bodyParser.json());
app.get('/backEndVersion.html', function (req, res) {
res.sendFile( __dirname + "/" + "backEndVersion.html" );
})
app.get('/somepath',function(req,res){
res.render('backEndVersion.html')
})
When u request somepath u will be rendered the backEndVersion.html file
I suggest u better use ejs or hbs engine for html renderering in nodejs
ejs link
I think you forgot to let the server listen to request. At the end of your file, add :
app.listen(8081)
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"
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());