سؤال

I need a corporate website with several pages

I've been able to produce that pages using below codes (using ECT template engine):

var http = require('http');
var url = require('url');
var ECT = require('ect');

var renderer = ECT({ root : __dirname + '/views' });
var data = { title : 'blabla' };

var front = renderer.render('front.ect', data);
var aboutus = renderer.render('aboutus.ect', data);
var ourtechnology = renderer.render('ourtechnology.ect', data);
var anypath = renderer.render('anypath.ect', data);

var server=http.createServer(function(req,res){
    var pathname=url.parse(req.url).pathname;
    switch(pathname){
        case '/':
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end(front);
        break;
        case '/aboutus':
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end(aboutus);
        break;
        case '/ourtechnology':
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end(ourtechnology);
        break;
        default:
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end(anypath);
        break;
    }

}).listen(80);
console.log('Server running');

But above codes are hardcoded.

How to make URL dispatching without hardcoding?

(I need to be able to create the page just like posting blog post)

I prefer MySQL for the database, and need guide where to start

هل كانت مفيدة؟

المحلول

Given your need, you should use express, then the problem becomes:

var express = require('express');
var app = express();

app.get('/', callback_for_root_dir);
app.get('/aboutus', callback_for_aboutus);
app.get('/ourtechnology', callback_for_ourtechnology);
app.get('*', default_callback);

app.listen(80);

Using MySQL for routing would be awkward, because how are you going to define the corresponding callbacks with a new path? You still need to code the callback in Node.js and restart the app, so there is no much point using MySQL data for routing. Besides, you can use powerful regular expressions for paths with Express.

نصائح أخرى

You can also use a library to extend express normal routing, and soft-code your routes even more.

https://github.com/hrajchert/express-shared-routes

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top