I'm having trouble locating my route for some unknown reason

I've set up a basic code structure to test my routes, but I keep getting a 404 error. Although I have an app.all function to catch errors, I'm having trouble pinpointing where the issue lies.

Below is my index.js file, where I've configured my express server and included the error catching app.all function:

const express = require('express')
const cors = require('cors')
const app = express()
const PORT = process.env.PORT || 8000

app.use(cors())
app.use(express.urlencoded({ extended: true }))

const userRoutes = require('./routes/users.js')

app.get('/', (req, res) => {
    res.send('Backend is up')
})

app.use('/', userRoutes)

app.all('*', (req, res,) => res.send('That route does not exist!'))

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

Here's my routes file, where I retrieve data from the users file:

const express = require('express');
const { getUsers, createUser, deleteUser } = require('../controllers/users.js')
const router = express.Router();

router.get('/users', getUsers)
router.post('/user', createUser)

module.exports = router;

Finally, here's my users file inside the controllers folder, where I handle setting up data for the client side:

const {v4 : uuidv4} = require('uuid')

let users = []

exports.getUsers = (req, res) => {

    try {
        res.send(users)
    } catch (error) {
        console.error(error)
    }
}

exports.createUser = (req, res) => {
    try {
        const user  = req.body

        users.push({...user, id: uuidv4()})

        res.send("User Added Successfully!")
        
    } catch (error) {
        console.error(error)
    }
}

Answer №1

Revise the following:

router.get('./users', getUsers)
router.post('./user', createUser)

to this:

router.get('/users', getUsers)
router.post('/user', createUser)

Avoid using ./ and ../ in route definitions. The route paths are already relative to the path that was used when the request was sent to that 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

Exploring the Benefits of Utilizing External APIs in Next JS 13 Server-side Operations

Can someone provide more detail to explain data revalidation in Next JS 13? Please refer to this question on Stack Overflow. I am currently utilizing the new directory features for data fetching in Next JS 13. According to the documentation, it is recomme ...

Having trouble updating the icon on my website using FontAwsome

Just a heads up - I'm not familiar with HTML/CSS/JS. This template is pre-made, and I'm simply making some adjustments to it. Hello, I'm currently working on my portfolio website and I want to display my projects based on the programming la ...

Tips for showcasing a designated set of numbers in Vue Js while iterating?

Is there a way to specifically target numbers during a loop? For example, I only want to retrieve numbers 5 and above or within a certain range that I specify. <select name="" id="input" class="form-control" v-model="selectcompetitionyear"> < ...

Issue with formatting and hexadecimal encoding in JavaScript

I am currently developing a LoRaWAN encoder using JavaScript. The data field received looks like this: {“header”: 6,“sunrise”: -30,“sunset”: 30,“lat”: 65.500226,“long”: 24.833547} My task is to encode this data into a hex message. Bel ...

What is the necessity of verifying that the password remains unchanged once the JWT has been generated?

I'm having trouble understanding why it's necessary to check if the password has been changed after issuing the JWT. I have a code snippet here that handles user authorization, but the reason for this specific check is unclear to me. Can someone ...

Maintain parental visibility with children when navigating to a different page

I am currently working on a vertical accordion menu that opens on hover, stays open, and closes when other items are hovered. The great assistance I received from @JDandChips has been instrumental in getting this feature up and running. Now, my main focus ...

Delete the designated column from the table

I am having difficulty with hiding and showing table columns using checkboxes. I need to eliminate the Mars column (in bold) along with its corresponding data (also in bold). Once the Mars column is removed, I want the Venus column and its data values to ...

How to effectively pass custom props or data to the Link component in Next JS

As I dive into Next JS, I've hit my first roadblock. Currently, I am working on a page that showcases various podcast episodes with preview cards on the homepage. The card component code looks like this: import React from 'react'; import Li ...

What's causing my variables to be returned as null in the alerts?

Why am I receiving null values when alerting my variables? I'm attempting to pass a string stored in a variable from an external JavaScript file back to the main page using alerts. Initially, I suspected that the JavaScript was not fetching data cor ...

Unexpected background image slideshow appearance

I am encountering an issue with my slideshow where the last image briefly appears before the first image loads in a continuous loop. The offset of the initial image causes it to start at the middle of the window, and in Google Chrome and Safari, subsequent ...

Encountering difficulties when attempting to store files using mongoose in a node express.js program

I encountered an error while attempting to save a document to the MongoDB using Mongoose in my Node Express.js project. Below is the code snippet: exports.storeJob = async (req, res, next) => { const { name, email, password, title, location, descri ...

The requested 'Pagination' component (imported as 'Pagination') could not be located within the 'swiper' library. Possible exports include Swiper and default

I was trying to implement pagination using swiper. I included the Pagination module with this import statement: import { Pagination } from "swiper"; Here's my configuration: The error that I encountered is : I have noticed that it w ...

What could be causing the "Undefned Jquery-ajax" error to pop up

I am struggling with the following code. My goal is to populate values into a dropdown <select> box, but I keep receiving an error of undefined. I have tried switching between Object.keys and Object.values, however, I am still facing the same issue. ...

Creating a large JSON file (4 GB) using Node.js

I am facing a challenge with handling a large json object (generated using the espree JavaScript parser, containing an array of objects). I have been trying to write it to a .json file, but every attempt fails due to memory allocation issues (even though m ...

Implementing CSS counter-increment with jQuery

Is there a way to use jQuery to set the CSS counter-increment attribute on ".demo:before" even though jQuery cannot access pseudo elements directly? I recall seeing a suggestion on Stack Overflow about using a data attribute and then referencing that value ...

What is the best way to send data from client-side JavaScript to node.js using XMLHttpRequest?

I have some HTML input fields in my index.html file. <input type="text" id="handle" > <input type="text" id="message" > <button id="send">send</button> After filling in the information and clicking "send", I want to pass this data ...

What is the best way to serve an index.html file in Express with the 'express-https-redirect' library in use?

I need help with the code below that is set to use HTTPS by default. I am unsure how to send an index.html file back var express = require('express'), path = require('path'), fs = require('fs'), app = express(), staticRoot = ...

Passing parameters to an Angular 2 component

When it comes to passing a string parameter to my component, I need the flexibility to adjust the parameters of services based on the passed value. Here's how I handle it: In my index.html, I simply call my component and pass the required parameter. ...

Setting the initial viewer position in Panolens: A step-by-step guide

I've been working on setting the initial viewer position for panolens.js for a while now. Here's how the set-up looks: const panoPhoto1 = 'https://conceptcityiasi.ro/assets/images/tours/tip1/apartamente-noi-de-vanzare-iasi-dacia-1_camera-ti ...

Problem Alert: Click Event Not Functioning on Generated Links

Take a look at these two code snippets. Despite other jQuery functions in the same JS file working fine on the UL element, nothing seems to be happening with these. Is there something obvious that I am missing? <ul id="activityPaganation" class="paga ...