简体   繁体   中英

Node.JS: Create new pages with Express

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM