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

React: Dynamic input field that removes default value as the user begins typing

Imagine a scenario where we have a text box in a React application with Formik and Material UI that accepts a price as a floating point number. By default, the field is set to 0. However, once the user manually enters a number, the default value should be ...

Encountering an issue while trying to deploy my node.js application on Heroku

While monitoring the Heroku logs using the command heroku --tail, I encountered the following error: Error: 2022-01-25T19:10:06.153750+00:00 app[web.1]: at emitErrorCloseNT (node:internal/streams/destroy:122:3) 2022-01-25T19:10:06.157055+00:00 heroku[rout ...

I'm looking to locate the API documentation for AngularJS TypeScript

After transitioning from using AngularJS 1.4 and plain JavaScript to now working with AngularJS 1.5 but utilizing TypeScript, I have found it challenging to find helpful documentation. For instance, when trying to inject services like $q or $timeout into m ...

The npm start command is no longer functioning in Angular 5

When attempting to start angular 5 with npm, I encountered an error that reads: TypeError: callbacks[i] is not a function Can anyone shed some light on where this error might be coming from? It seemed to pop up out of the blue and I can't seem to ...

Inspecting Mapped Data in React using the Console

For some reason, I am unable to console.log any selection when using onClick in this React component. My goal is to achieve the following functionality. https://codesandbox.io/s/great-ardinghelli-6seko?file=/src/demoComponent.jsx I have successfully fetc ...

What is the best way to showcase the current date and time on a web browser

Currently working on a nodejs express application where dates are stored in the database using UTC date/time. Want to display the date/time in the user's local time zone. Any ideas on how I could go about implementing this? Appreciate any assistance. ...

Using dustjs-linkedin alongside express version 3

Attempting to integrate dustjs-linkedin with an express 3 project, encountering a persistent error: Error: Template name parameter cannot be undefined when calling dust.compile at Object.compiler.compile (/home/user/project/node_modules/dustjs-linkedin/li ...

The challenge of populating information within a Datalist

In my code snippet, I have a JavaScript function that is used to populate a Datalist: function PopulateDropDown(facility) { $.ajax({ url: '/Rentals/Base/GetContactsForFacility?selectedFacility=' + facility, data: { facility: ...

Why is the model so tiny after converting my FBX file to a .gltf format?

QUERY: I am facing an issue where my model appears extremely small after converting the FBX file to a .gltf format. Despite attempting to scale the model using frontObject.scale.set(1000, 1000, 1000);, I encounter the following error: TypeError: Cannot r ...

React: Modifying a single input field out of many

Can someone please review this code snippet: https://stackblitz.com/edit/react-koqfzp?file=src/Section.js Whenever I add an item, a random number is also added that I want to be able to edit. This number is displayed in a Material UI Text Field component. ...

Sharing an array between two sibling components

Within my 'Home' component, users have the ability to create QR codes. I have implemented a method that generates an array of these QR items. Now, the challenge lies in passing this array to another component that is a sibling and not located wit ...

Can you explain the function of this.$nextTick()?

I'm a beginner with Vue.js and I'm trying to wrap my head around the logic of using nextTick in a method. I have two components set up like this: IsTuruIslem.vue <template> ... <t-row> <is-turu-islem-goruntule ref="isTuru ...

Verify if the JSON response contains any data

When the JSON response is empty and viewed in the browser console, it appears like this: {"data":{},"status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://url/form/BN217473" ...

Vue.js throws an error because it is unable to access the "title" property of an undefined value

I am currently facing an error and unable to find a solution. Even after changing the title to 'title', the error persists. methods.vue: <template> <div> <h1>we may include some data here, with data number {{ counter ...

Send information to a Google form using AJAX requests

I have encountered an issue while attempting to send data via AJAX to a Google form. Despite receiving a success message with a statusCode of 0, the data does not show up in the form: var dat={ "entry.529474552" :"data1", "entry.1066559787": "name1"}; pos ...

Mapping out your data effectively requires following the correct steps to ensure accuracy and clarity

My goal is to display a map using Mapbox only once the data is ready. The Vuex store code I am working with is as follows: /store/index.js import Vue from "vue"; import Vuex from "vuex"; import _ from "lodash"; import { bac ...

angularjs issue with $setPrestine function not providing reliable results

I have encountered an issue with the login form code. Initially, I am able to reset the form fields and error messages successfully on the first attempt (both success and failure scenarios work). However, on the second try, I am unable to reset the form fi ...

Understanding the response from an AJAX call

VB code Dim temp3 As String = dt.ToString() cmd.Connection = con con.Open() i = cmd.ExecuteNonQuery() con.Close() If i = 1 Then msg = "Record successfully inserted" ...

Tips for successfully transferring an image through an XMLHttpRequest

I found this helpful resource at: I decided to test out the second block of code. When I made changes in the handleForm function, it looked like this: function handleForm(e) { e.preventDefault(); var data = new FormData(); f ...

Issue with Magento: Unable to execute dataflow profiles due to Ajax Error (Uncaught TypeError: e is not a function)

Whenever I try to execute a dataflow profile in Magento, the following series of events unfold: The CSV file is uploaded successfully X rows are found A message displays: Starting ... :: saveRow (handler-method) However, a JavaScript error interrupts th ...