How to create absolute links in Node.js?

I am using Node.js with Express, Connect and Jade. I want to provide an absolute route link in my application, but I cannot find how to do this. I have to skip something because this seems like a simple task.

I can do this: / myroute

But I want this: http: // localhost: 3000 / myroute

There must be an assistant somewhere, right?

+4
source share
3 answers

I created for myself my assistant, which does not seem to be the best solution.

Helpers = { toAbsolute: ( url, req ) -> 'http://' + req.headers.host + url } DynamicHelpers = { req: ( req, res ) -> req } exports.Helpers = Helpers exports.DynamicHelpers = DynamicHelpers 

I add helpers to the app.coffee file:

 helpers = require './helpers.js' # Helpers app.helpers helpers.Helpers app.dynamicHelpers helpers.DynamicHelpers 

In my [jade view], this is what I do to get the absolute URL from the relative URL:

 | <a href="#{ toAbsolute( '/relativeUrl', req ) }">link text</a> 
+3
source

There is no β€œhelper”, but you can write your own by introducing req.query variables into local jade variables for the route.

Personally, I would do this on the client side using window.location.origin.

+1
source

update : in fact, this only works if req is POST, not GET .: (

update 2 : ugh, it is not even consistent between browsers. and is not a tim. To find the solution I ended up google "window.location.origin is considered harmful."


req.headers.origin seems to return something like http://example.com:1234 'when the browser clicks http://example.com:1234/something '.

this seems to be the expressed equivalent of @timoxley's client solution. :)

It's a little easier than yours, but it eliminates the need for literal "http" (or https).

0
source

Source: https://habr.com/ru/post/1392282/


All Articles