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

Error: AJAX requesting page not listed in manifest

When using a cached HTML page and JQuery, I've encountered difficulty accessing a page from the server that is not listed on the manifest. Every attempt I make to access a page not included in the manifest results in a return of null or an empty strin ...

Can you explain the process of utilizing a JavaScript function that has been fetched via Ajax

When the AJAX function is loaded on the page, I am attempting to execute another function. The code snippet for the AJAX call: $.ajax({ type: "POST", url: "loginpersonal.asp", data: "id=<%=request("id")%>", beforeSend: function() { $("#personal ...

PHP code cannot be outputted to JavaScript due to a syntax error

Although there is a syntax error, the code seems to be working. I am curious about how to make it syntactically correct. The provided code snippet is part of a script that sets up variables for an Ajax call. Depending on the scope, the corresponding varia ...

Don't forget to save the toggleClass state to local storage in jQuery so it persists after

It's a challenge to maintain the value of toggleClass after refreshing or reloading the page. I have a structured table where rows toggle visibility when clicked. To preserve these toggle values, I utilized localStorage, but unfortunately, the state i ...

Steps to troubleshoot the TypeError: cv.Mat is not a constructor in opencv.js issue

Encountering a problem while trying to use opencv.js for detecting aruco markers from my camera. Each time I attempt to utilize the method let image = new cv.imread('img'); An error keeps popping up: TypeError: cv.Mat is not a constructor ...

Error with JSON data from the Twitch TV API

I am having trouble with the Twitch API. When a streamer is live, I work with the "Stream" property, but if they are not streaming, I need to refer to another link. I use the getJSON function to fetch the necessary API link and work with it. However, my lo ...

dynamic text overlay on a bootstrap carousel

Having limited knowledge in html and css, I am using a bootstrap carousel slider with text. I am trying to change the color of the box randomly. https://i.sstatic.net/TozUP.jpg Here is the code that I am currently using: <ol class="carousel-indicato ...

Oops! An error occurred while trying to find the _mongodb._tcp.blog-cluster-0hb5z.mongodb.net. Please check your query settings and try again

My free Mongo Atlas cluster suddenly stopped connecting, even though everything was working fine before. Strangely, I can see that data has been collected on the MongoDB website. It's puzzling why this issue occurred and now my entire site won't ...

What is the method for transmitting a message from localhost to a React frontend?

I am currently running a WebSocket server that is receiving streams of messages from an MQTT source. These messages are then sent to a localhost server on port 8080. The messages being received are actually a stream of random numbers. Below is the Python ...

Error: Mongoose Schema Undefined when Route is Added in Separate File

For the sake of organizing my code, I made the decision to separate all of my schemas and routes into different files within my directory, and then required them in my app.js. Each schema corresponds with each route. This method has worked for all but one ...

Having trouble with a peculiar for_of loop issue in Node.js: struggling to iterate correctly

Currently immersed in a Python project, I find myself in need of retrieving data from a Node.js API. Despite my limited knowledge of Node.js, I attempted to write some code for this purpose. Here is the code snippet: const SneaksAPI = require('sneaks ...

What is the method to set precise values on a range slider?

Currently, I am developing a PHP website that requires a slider for displaying the years of publications. In essence, I need the slider to navigate through the different years when the publications were released. // Database connection and other PHP code ...

Retrieve error messages from the controller using Ajax and send them back as JSON

I'm having trouble retrieving errors from my form as the return value is empty, even though the data is being received by the controller. Valid forms are processed without any issues. Below is a snippet of my code : if ($request->getMethod() == & ...

IE9 experiences difficulty with Ajax-based authentication

I have integrated Ajax-based login and signup functionalities within a Fancybox modal. When a user clicks on the login button, the form inside the Fancybox opens, the user submits the form, and the page reloads with the user being authenticated. I'm u ...

Passing an object in Vue.js during a redirect

i currently have two components named projectListComponent and projectSingleComponent. I want to pass an object from component 1 to component 2 during redirection. Here is my code: projectListComponent.vue <template> <div class="row justify ...

Post the information from a webpage onto your Instagram story

I'm currently developing a web application that generates text content, with future plans to include images as well. I want to integrate a share button that allows users to easily add this generated content to their Instagram story. The intended flow ...

Exploring AngularJS's Unique Features: Isolated Scope and Controller Connection

Currently, I am diving into Angular and endeavoring to develop a Phone Message Log application utilizing directives. The concept is simple - the user inputs a message, clicks a button, and it gets displayed in a "Message" log below. The challenge I'm ...

Transform static borders into mesmerizing animations by changing the solid lines to dotted lines using CSS

I've managed to create a circle animation that is working well, but now I'm looking to switch from solid lines to dotted lines. Can anyone provide guidance on how to accomplish this? Here is the current appearance: #loading { width: 50px; ...

What is the method to determine the index of a removed element within a subarray?

In my array, all = [2,3,4,12, 55,33], there is a sub-array named ar1 = [12, 55, 33] starting from the value 12. If I remove a value from all that is present in ar1 (e.g. 12), how can I determine the index of this value in ar1 (0 for 12) so I can also remo ...

Searching and paginating through custom post types using an ajax call with $wpdb

I have recently developed a customized post type called "news" using Wordpress, and I am looking for a way to search through these posts and implement pagination without causing page reloads. Currently, I am utilizing the $wpdb class which is functioning ...