ax1/a1-server

implement core method to retrieve the request fullHOST

Opened this issue · 1 comments

ax1 commented

FullHost better than fullURL because:

  • it is usually intended to concatenate the baseurl with other paths, so no need to cut and replace, just concatenate
  • get the full url is dead simple req.util.fullHost()+req.url

Current request[incoming message] does not have the protocol. Express add it on each request.
It could be useful to add a request.util={methods} so the performance is not harmed on each request (no data manipulation, only adding a reference) and access to utils methods without importing 'a1-server/util' or similar

The idea appear because when sending a REST post, the location url can be relative but it could alsobe useful to send the fullurl in the response payload, so the dev client can just call instead of concatenate urls. The problem in stnadard request is that the protocol(http/https) is not sent. Express has the protocol property built in but as mentioned above it is better to add those things as an only reference (normal services same speed of request while services needing more data have a handy way to guess/concatenate request properties)

For the host name take into account proxy redirection headers and so on

the simplest way to detect protocol is:

function fullHost(request) {
  const protocol = (request.connection.encrypted || request.headers['x-forwarded-proto'] === 'https') ? 'https' : 'http'
  return `${protocol}://${request.host}`
}
ax1 commented

If no proxy, fullHost is a trivial concatenation. If reverse proxy (eg: NGINX), some headers must be set there. After googling and finding no standard solutions and often 'exotic' ideas, best is to send a custom header with the fullHost, instead of sending several headers (real host and real path). This method works either direct call or via proxy.

/**
 * Real host is not available in the request. Only the internal host. For reverse proxy redirection, another header must be set to know what is the real host for the caller to concatenate th URL
 * @param {*} request 
 */
function fullHost(request) {
  const protocol = (request.connection.encrypted || request.headers['x-forwarded-proto'] === 'https') ? 'https' : 'http'
  const host = request.headers['host']
  return request.headers['x-forwarded-root'] ? request.headers['x-forwarded-root'] : `${protocol}://${host}`
}
location /mypath/ {
          proxy_pass http://localhost:9999/;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-Root
          $scheme://$host/mypath;
}