[Fixed] Node express: dynamically creating a full body link with all attributes?


In a node-express app, I made a function to generate public links, for in this case I want to show a login-link in a view "http://example.net/login/123/tokenishfoobaarchinsignsignisgn"

function link_to(req, path){
  return `${req.protocol}://${req.hostname}/${path}`

This works OK in production where port is 80 by default.

Though I’m not finding a method on req where I can fetch ports to see if PORT != 80?

I would like to be able to have this know if I’m accessing via localhost:3001 for instance, to be able to add this to link-function. And/or is there a better way to have this type of link-generator functionality from express?



AFAIK port is not available on the req object (the rest of what you need is). Normally you know what port your listening on because you provide it to express via the call to listen(), although it’s possible to not provide in which case a random port is assigned.

If you need the port, you can get it from the HTTP Server instance returned from listen():

var express = require('express')
var app = express()
var server = app.listen() # Random port is assigned if not provided as 1st arg.

Leave a Reply

(*) Required, Your email will not be published