Is it possible to change the URL with NodeJS?

Right now, I have two paths set up:

app.get("/post/:id", ...

and

app.get("/post/:id/:title", ....

I want to be able to get the incoming post/:id path and then search the database, get the mongo, etc, etc… at the end, I want to grab the title from the doc and then change the url (redirect) to /post/:id/:title.
I’m considering passing the whole found document to EJS, and then using the window.redirect global function to change the url to the new one.

Something like

window.redirect = `window.location.href/${data.title}`

Is it possible to use EJS variables inside of native JS tags (<script>)? The global window object isn’t present in ejs <% %> tags.

Assuming you’re using express js something like …

res.redirect("/post/${id}/${title}")

The title might need url-encoding.

4 Likes

I have a regex replacement set up for spaces. I’ll try that - thanks!

Thanks! I got my app to work. On a side note, Express automatically parses incoming ASCII-encoded URIs - the path !%40%23%24%25%5E%26*()_%2B automatically converted to !@#$%^&*()_+ in the response body.