Express: Dynamic routing

Created on 7 Mar 2019  路  1Comment  路  Source: expressjs/express

I am writing a simple server that calls default url '/', Get '/articles' , Post '/user' information and Put '/logout' requests.

Here is my code below

const http = require('http')
const express = require ('express');
const app = express();

const host = '127.0.0.1'
const port = 3333 || process.env.PORT

http.createServer(preprocess).listen(port, host)
console.log(Server running at http://${host}:${port})

function preprocess(req, res) {
let body = ''
req.on('data', function(chunk) {
body += chunk
})
req.on('end', function() {
req.body = body
console.log(body)
server(req, res)
})
}

function server(req, res) {
console.log('Request method :', req.method)
console.log('Request URL :', req.url)
console.log('Request content-type :', req.headers['content-type'])
console.log('Request payload :', req.body)

 const payload = serverResponse(req.url, req.body)
 res.setHeader('Content-Type', 'application/json')
 res.statusCode = 200
 res.end(JSON.stringify(payload))

}

function serverResponse (reqType, reqData) {

var serverRes
//console.log(reqData);

switch(reqType) {
case '/' :
serverRes = { 'hello': 'world' }
break;

case '/articles':
  serverRes = {articles: [{id: 1, author: 'LMN', body: 'A post'} ,
      {id: 2, author: 'ABC', body: 'post 2'},
      {id: 3, author: 'XYZ', body: 'post 3'} ]}
  break;

  case '/user' :
    try {
        var data = JSON.parse(reqData);
        serverRes = {"username" : data["username"], "result":'success'}
        console.log("Server Response: " + serverRes)
      } catch(e) {
        return 'malformed request';
    }
    break;

  case '/logout' :
    serverRes = 'OK'
    break;

  default: break;

}
return serverRes;
}

I wanted to know if it is possible to have dynamic URL like for example "/user/name1", "/user/name2".

I know we can implement dynamic routing as below:

app.post('/user/:name' , function (req,res) { .... } );

I want to implement the server as http and hence, the workaround won't help. Any suggestions on how to have dynamic routing with expressjs and http?

Most helpful comment

So that would be a question for the node.js project if you are not using express.js. if you're using express then app.post('/user/:name' is how you do it. Otherwise you just have to write your own routing, at which point, just use express?

>All comments

So that would be a question for the node.js project if you are not using express.js. if you're using express then app.post('/user/:name' is how you do it. Otherwise you just have to write your own routing, at which point, just use express?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

HafidAbnaou picture HafidAbnaou  路  3Comments

jefflage picture jefflage  路  4Comments

guyisra picture guyisra  路  3Comments

ER-GAIBI picture ER-GAIBI  路  3Comments

wxs77577 picture wxs77577  路  3Comments