Implementing dynamic URLs using static routing in Express

I'm looking for a way to render a page statically in Express that involves using a dynamic URL.

For example,

In my forum, users create posts and each post has its unique URL that shows the post when clicked:

localhost:8080/posts/postNumber

Currently, I have a static HTML page at localhost:8080/posts/.

I want the dynamic links that users click to display the content of the static page at localhost:8080/posts/, but still show the original dynamic URL localhost:8080/posts/postNumber, so I can use the post number with an AJAX request.

Is there a way to achieve this without resorting to dynamic rendering as I am attempting?

Answer №1

If you need to define URL parameters, you can do it in the following way:

app.get('/posts/:postNumber/', function (req, res) {
   // Here you can work with req.params that will hold
   // {postNumer: yourValue}

    var options = {
        root: __dirname + '/public/',
        dotfiles: 'deny',
        headers: {
          'x-timestamp': Date.now(),
          // any other needed headers
        }
    };

    var fileName = 'staticFileName';
    res.sendFile(fileName, options, function (err) {
       if (err) {
         next(err);
       } else {
         console.log('Sent:', fileName);
       }
    })
})

This code snippet will correspond to /posts/[anything_you_want] and transmit the specified filename fileName from the directory set in the options. This information is sourced from the express 4 documentation available at: http://expressjs.com/en/api.html#res.sendFile

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring object manipulation and generating unique identifiers by combining values - a beginner's guide

After analyzing the provided data, my goal is to come up with a method of combining the IDs and returning an array of their corresponding keys. // example data var data = [ { id: 1, key: 'a' }, { id: 1, key: 'b' }, { id: 2, key ...

When attempting to use the search bar to filter in ReactJs, an error occurs: TypeError - Unable to access properties of undefined (specifically 'filter')

When I receive data from my JSON server on the console, everything looks good. But when I try to type something in order to filter it, an unhandled error occurs with the message: 1 of 1 Unhandled Error Unhandled Runtime Error: TypeError: Cannot read prop ...

There are no functions or classes returned when using NPM Link with the module

Welcome. Whenever I run npm link ../folder/ToFolder, it works as expected. However, when I attempt to import any function, nothing is returned. A clearer explanation I have tried importing a module that I created from another folder using npm link. When ...

React: Import default export as a string

Help needed with JSON data import import dataOption1 from './Option1.json' import dataOption2 from './Option2.json' async setParamsByDomain(optionUser) { await this.setState({ jsonName: "data"+ optionUser}); console.log(t ...

Guide on transferring files and directories to a functioning directory within a Dockerfile

Issue My node application has a straightforward setup, with the following file structure: ├── Dockerfile ├── app.js ├── bin │   └── www ├── package.json ├── public │   ├── images │   └── stylesh ...

Tips for performing an integration test on a material UI <Slider /> component using either userEvent or fireEvent

I'm facing some challenges while trying to perform an integration test on a material UI component. I can locate the slider element, but have not been successful in moving the slider and retrieving the new value. Can you provide any guidance on how to ...

Which specific html container or element can be found on the mymsn pages?

When accessing mymsn, users have the ability to personalize the content and layout of their webpage. I am curious about what type of container is being utilized for this customization - does it involve an html element, or perhaps javascript, or something e ...

Error with XMLHTTPRequest loading in beforeunload/unload event handlers in iOS 13.4.1 encountered

Currently, I am utilizing XMLHTTPRequest for data posting in JavaScript. Previously, it functioned smoothly on Safari and Chrome browsers up to iOS 13.3.1. However, upon updating to the latest OS version, iOS 13.4.1, an error message stating "XMLHTTPReques ...

Editing an XML file on the browser and saving it in its original location on the local file system

Seeking assistance with editing an XML file directly from the browser on a local file system and saving it back to its original location. I have conducted extensive research using Google, but have not been able to find a suitable solution. Any help or gu ...

Building the logic context using NodeJS, SocketIO, and Express for development

Exploring the world of Express and SocketIO has been quite an eye-opener for me. It's surprising how most examples you come across simply involve transmitting a "Hello" directly from app.js. However, reality is far more complex than that. I've hi ...

Can you terminate an AJAX request sent to a Windows server 2012 / IIS8?

Is there a way to notify the server from the front end UI to skip processing some of the 10 ajax requests that are queued up and being processed one by one? ...

Using ES6 syntax, ignite the React function

Below is the code snippet provided: class Seismo extends Component { constructor(props) { super(props); this.state = { news: "" } this.updateNews = this.updateNews.bind(this) } updateNews = () => { console.log('te ...

a guide to presenting information in a horizontal layout within a single table using the Laravel framework and Vue.js

I have 2 tables: table 1 ________________ | name_id name | | 1 john | | 2 heaven | |_______________| table 2 _______________________ | id name_id product | | 1 1 bag | | 2 1 shoes | |______ ...

Adding a regional iteration of a library that was unable to be loaded

Recently, I have been experimenting with PhantomJS to capture screenshots of a webpage every five minutes. While the process runs smoothly most of the time, I encountered an issue where the AngularJS library fails to load intermittently. This results in th ...

Instructions on how to activate scrolling for a div element that becomes visible upon clicking a button

When a button in the navbar is clicked, a div appears with a height that exceeds the viewport/page size. How can I enable scrolling for the entire page when this happens? I attempted to use overflow: scroll, but it only applied scrolling to the internal d ...

The impressive Mean.io framework integrated with the powerful socket.io technology

Looking for guidance on integrating socket.io in the Mean.io stack? I've noticed that Mean.io frequently changes their folder structure, so I'm wondering where the best place is to configure socket.io. Should I use express.io instead? I'm ...

Ways to verify if TypeScript declaration files successfully compile with local JavaScript library

I have recently updated the typescript definitions in HunterLarco/twitter-v2, which now follows this structure: package.json src/ twitter.js twitter.d.ts Credentials.js Credentials.d.ts My goal is to verify that the .js files correspond correctly ...

Issue with resetting Knockout.JS array - unable to make it work

Hey everyone, check out the project I'm currently working on over at Github: https://github.com/joelt11753/Udacity-map In this project, I have a menu generated from a list that can be filtered using an HTML select element. Initially, all items are di ...

JavaScript encountered an issue as it attempted to reference the variable "button" which was

I am currently working on developing a new API, but I have encountered some issues with JavaScript: Below is my JS/HTML code snippet: const express = require('express'); const app = express(); const PORT = 3000; submit.onclick = function() ...

What is the best way to store HTML in a variable as a string?

Imagine if I have a variable: let display_text = "Cats are pawsome!" I aim to show it as such: <div> <b>Cats</b> are pawsome! </div> To be clear, dynamically enclose the word "cats" whenever it shows up. ...