The router.get function seems to be malfunctioning, however when using the router.get function with an id

When I call http://localhost:5000/surveycreate/4, it successfully redirects me to the surveypage.html page.

However, calling http://localhost:5000/surveycreate does not work as expected. Instead of redirecting me, it leads me back to my main index.js file in the public folder without even displaying "regular get".

I'm puzzled why this is occurring?

The surveypage.js route includes:

const path = require("path");
const router = express.Router();

router.use(express.static(path.join(__dirname, "../public")));

router.get('/:id', async (req, res) => {

  console.log("get with id");
  res.sendFile(path.join(__dirname, "../public/Surveypage.html"));

})

router.get('/', async (req, res) => {

  console.log("regular get");
  res.sendFile(path.join(__dirname, "../public/Surveypage.html"));

})


module.exports = router; 

Answer №1

Ensure that your file structure aligns with your code for optimal functionality.

Here is an example of code that has been performing well:

app.js:

const express = require("express");
const app = express();
const cors = require("cors")
const surveyPage = require('./routes/surveypage')
const path = require("path");
const PORT = process.env.PORT || 5000

app.use(express.json());
app.use('/surveypage', surveyPage)
//app.use(express.static(path.join(__dirname, "/public"))); // not necessary
app.use(cors())


app.listen(PORT, () => console.log(`Listening on port ${PORT }`))

surveypage.js

const path = require("path");
const express = require('express')
const router = express.Router();

router.use(express.static(path.join(__dirname, "../public")));
router.get('/:id', (req, res) => res.sendFile(path.join(__dirname, "../public/Surveypage.html")));
router.get('/', (req, res) => res.sendFile(path.join(__dirname, "../public/Surveypage.html"))

module.exports = router;

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

What could be causing my jQuery code to not function properly?

I wrote a small piece of code in jQuery, but I am having trouble executing it. Can someone help me figure out what I'm doing wrong? <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"> & ...

Ways to retrieve the React Router match object in mapStateToProps

Is there a way to access the react-router match object for its params from mapStateToProps or any other selector? I'd like to use these params to generate a value that will be passed down as props to a presentational component within the selector. The ...

Issue with React Native and Redux: Prop values are updating without being called

I'm currently facing a problem with React Native and Redux integration. Using a Redux state to toggle a modal visibility between components seems like the most efficient solution due to its cross-component nature. The modal opens and closes as expec ...

I've been attempting to relocate a CSS element at my command using a button, but my previous attempts using offset and onclick were unsuccessful

I am trying to dynamically move CSS items based on user input or button clicks. Specifically, I want to increment the position of elements by a specified number of pixels or a percentage of pixels. Currently, I am able to set the starting positions (top a ...

Iterating through a jQuery function to increment value

I have encountered an issue while trying to calculate the total value from an array of form fields. The problem lies in how the final value is being calculated on Keyup; it seems that only the last inputted value is being added instead of considering all t ...

How come my post isn't being saved to the page after I refresh it?

Utilizing Javascript, NodeJS, MongoDB, Express Within my application, a user is expected to enter text in an input field and upon clicking the submit button, the text should appear on the page. I have succeeded in posting text to the page; however, after ...

Monitor the execution of JavaScript callbacks without the need for layering functions

Currently, I am developing a function that involves multiple database calls and needs to store their results in an array before triggering a callback. Let me share some pseudocode for better understanding: function getData (array, callback) { var resu ...

Utilizing Codeigniter and Angular JS: Getting the Most Out of Partials

Let's dive into the current scenario: I'm in the process of developing an application using Codeigniter and Angular Js. At present, it's a basic app that retrieves data from a database and showcases it in a table format. To enhance the fun ...

Utilizing Python, Javascript, and AJAX to enhance the live search functionality

I am currently working on developing an AJAX live search feature using Python. Being new to AJAX, I have been learning from various tutorials and documentation to make progress. While searching, I came across an example at http://www.w3schools.com/ajax/aja ...

The Cordova Network Information Plugin is experiencing some functionality issues

I successfully developed a Mobile application using Cordova, Onsen UI, and Vue.js. While addressing network connectivity issues, I incorporated the cordova plugin cordova plugin add cordova-plugin-network-information For determining the type of connectio ...

Tips for extracting data from a JSON file

I'm attempting to retrieve a list of music genres from my json file using PHP and JQuery ajax. Here is the format of my json file [ "12-bar blues", "2 tone", "2-step garage", "4-beat", "50s progression", "a cappella", "accordion", " ...

Running a Gulp task to launch an express server

Within the same directory, I have both a server.js file and a gulpfile.js file. In the gulpfile.js, I am requiring the server.js file: var express = require('./server.js') My intention is to run it within the default task: gulp.task('defa ...

When the mouse hovers over the slider, the final image jumps into view

After successfully building an image slider that displays 2 partial images and 1 full image on hover, I encountered a bug when setting the last image to its full width by default. This caused a temporary gap in the slider as the other images were hovered o ...

Can the input type of an input element inside a table cell be altered by referencing the table cell's id using javascript?

Need help with changing the type of an input element from password to text using JavaScript? The input element is located inside a <td> with the id "pass". Also looking to add a checkbox that toggles displaying or hiding the password value. I'm ...

What is the best way to show "no results found" message in a jQuery search list?

Everything is working smoothly. Does anyone have any suggestions on how to display a message saying "No results found"? This is the code I'm using: http://jsfiddle.net/UI_Designer/8p426fog/4/ $(".my-textbox").keyup(function() { var val = $( ...

The total sum of values within labels that share the same class

I am attempting to sum up all the values of class tmpcpa and store the result in final_cpa, but for some reason final_cpa always ends up being 0. document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label id="tmp ...

Application for Android: Transferring JavaScript Variable to Native Java Variable

I'm developing an Android App and I have a piece of javascript code that is being loaded from "str8red.com" within a webview: <script>var name = "bob", age = 30;</script> There's a textbox in the app that I can set using: textView. ...

Limiting the input frequency when executing a query with the `urql` GraphQL Client in React.js

My slider functions similarly to this one from Zillow's GitHub. It has minimum and maximum values, and triggers a query whenever the sliders are adjusted. The issue I'm facing is that the query is extensive, causing delays. I am looking for a wa ...

Retrieving URLs of mapped image array from Firebase using React

I have successfully implemented an image slider in my website using https://github.com/kimcoder/react-simple-image-slider. This slider takes an array of images as input through Object.values(images). However, I now want to switch to using a grid array prov ...

Returning a PHP variable to AJAX communication

if($rx==$_SESSION['randomx'] and $ry==$_SESSION['randomy']){ echo "Congratulations, you hit the correct cell! You only used:".$_SESSION['poskus']; } else{ $distance=sqrt(($rx-$_SESSION['randomx'])*($rx-$_ ...