Trying to create static web pages with the help of express framework

Currently, I am facing an issue while setting up specific pages on my localhost server. When a user visits locahost:number/war, they should be able to see the /war page. However, upon running the server, I encounter a "Cannot GET war" error on the page. This setup has worked for me in the past without any problems.

I have also noticed a "ReferenceError: __dirname is not defined" message in the console.

import express from 'express';
const app = express();
const router = express.Router();
import path from 'path';
import {getData} from './server.js'

// HTML Routes

router.get('/', (req,res)=> {
    res.sendFile(path.join(__dirname, "../start.html"));
})
router.get('/war', (req,res)=> {
    res.sendFile(path.join(__dirname, "../index.html"));
})
router.get('/score', (req,res)=> {
    res.sendFile(path.join(__dirname, "../finalScore.html"));
})

// Data
export async function sendStats(){
app.get("/data", (req,res)=> {
    const data = getData()
    res.json(data)
})
app.post("/data",(req, res) => {
    const {name, score} = req.body
    const data = createData(name, score)
    res.json(data)
} )
app.use((err, req, res, next) => {
    console.log(err.stack)
    res.status(500).send('Something Broke!')
})
app.listen(7171, ()=> {
    console.log('Server is running on port 9191')
})
}
const data = await sendStats();

Answer №1

Don't forget to include the router in your app setup:

app.use('/', 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

Challenges with handling form elements in JavaScript

I'm currently developing a project and facing challenges in implementing input validation for a form. My goal is to ensure that the form only gets submitted and redirects to a specific URL if all requirements are met. To achieve this, I am utilizing J ...

Interactive button visual effect

I have a piece of code that currently plays audio when I click on an image. However, I am looking to modify it so that not only does clicking on the image play the audio, but it also changes the image to another one. Can anyone assist me with this? Here i ...

Randomize the array of images in Nuxt every time the page is reloaded to display a variety of logos in the carousel

I've set up a carousel of logos, with the intention to randomize their order every time the page reloads. The challenge is that my layout only allows for 10 images to be displayed at once. While it seems like everything is functioning correctly, I&ap ...

Tips on incorporating the wait function within the evaluation_now action in Nightmare?

While I am incorporating Nightmare actions in my script, a question arises regarding the use of the wait function within the evaluate_now function. How can I utilize the wait function within the evaluate_now function? I am aware that I can simply use the ...

Vue.js does not apply the "selected" attribute to set the HTML <option> tag to default

Trying to designate a default <option> tag from the available options. Utilizing v-model on the <select> tag, the vue.js documentation indicates the following approach: v-model will disregard the ... selected attributes present on form ele ...

Is there a way to halt this interval once it reaches the end of the array?

I am attempting to create a simple animation using an array where it types out my name in a similar fashion to a command prompt. This is my first experience with React hooks, so I am feeling a bit lost. My goal is to have the interval stop at "Felipe Garci ...

React - The mechanics behind a spinning roulette wheel

I've been attempting to create a React roulette spinner but I've encountered some issues with the transitions and functionality. Here is the initial version of the algorithm: The callback functions are triggered whenever the 'winner&apo ...

Exploring and deciphering the intricacies of the underlying technology

Apologies if this question seems misplaced, but as a complete beginner, I'm a bit lost. Let's consider this website as an example: I'm trying to uncover the libraries and technologies employed in the background to learn more and replicate ...

Develop a constructor that can be injected

Delving into the world of AngularJS as a beginner, I am starting to grasp the intricacies and distinctions between factory, service, and controller. From my understanding, a factory serves the purpose of returning a "value object" that can be injected. Mos ...

Contrasting the inclusion of the "route" keyword when defining routes in Express

Can you explain the distinction between router.route('/create') .post(validate(hotelValidation.createHotel), function (req, res) { and just router.post('/create', validate(hotelValidation.createHotel), function (req, res) { Are ...

Enhancing auto-suggestion layout using JQuery

I have implemented a custom autocompletion plugin for my project. It's designed to fetch data from a specified URL and provide auto-complete suggestions based on the input. Below is the code snippet I am using for auto-completion: autocompleteurl = ...

What causes the discrepancy in results between the quoted printable encoding operation in JavaScript and Oracle?

Programming Languages: // JavaScript code snippet //https://www.npmjs.com/package/utf8 //https://github.com/mathiasbynens/quoted-printable par_comment_qoted = quotedPrintable.encode(utf8.encode('test ąčęė')); console.log('par_comment_qot ...

Refreshing a page using AJAX form functionalities

After spending some time searching, I am unable to find a satisfactory solution to my issue. I have a "finance" tracker that includes hidden divs which are displayed using jQuery when the corresponding button is clicked. Additionally, I have an Asset Track ...

VueJS causing roles checking to run forever, creating an infinite loop

Customizing the navigation bar to display elements based on user roles: <b-navbar-toggle right class="jh-navbar-toggler d-lg-none" href="javascript:void(0);" data-toggle="collapse" target="header-ta ...

Having trouble with Next-Auth's signIn with Credentials feature in NextJS?

I have recently added the next-auth package to my new Next.js project. Despite following all the documentation for both Next.js and next-auth, I am still unable to resolve the issue. The problem I am encountering is as follows: I am trying to log in to my ...

Eradicate HTML by assigning empty values to certain attributes

Allowing the user to copy the HTML code of a div by clicking a button. Some attributes, such as for videos: <video loop muted autoplay> may appear like this after copying: <video loop="" muted="" autoplay=""> The ...

Developing a personalized child node on Firebase's real-time database using React Native

Seeking assistance as a newcomer to Firebase and React, I've exhausted all my options and appreciate any help you can provide. Here is the data structure I am using in Firebase: https://i.sstatic.net/fKtdK.png When adding a new Beverage type, such ...

I can't seem to figure out why the getContact API call is continuously running without any errors. Can you suggest a solution to

//@desc Retrieve contact information //@route GET api/contacts/:id //@access public const getContactInfo = asyncHandler(async (req,res) => { const data = await Contact.findById(req.params.id) console.log(data); // Line 6 if(!(await data)){ ...

Arranging an array based on various conditions and criteria

I am struggling to incorporate sorting and ordering into an array. The obstacle I am encountering involves having 5 criteria for sorting, which are: due_date === 1000 status && is_approved(boolean) is_overdue(boolean checking with date-fns using ...

displayEvent not functioning properly within fullcalendar

I'm attempting to add an event to FullCalendar.io using a JavaScript function. I've tried two methods. Triggering the function at the end of the page or by clicking. No error is displayed, but the event isn't showing up on my calendar. & ...