Issues with routing in NodeJS Express causing routes to not be called

I've been working on setting up a basic REST API using nodeJS. However, I am facing an issue where none of the endpoints are being called when I try to access them. Can someone guide me on what changes I need to make in order to get it working properly? Any help would be appreciated.

const express = require('express') ;
const app = express() ;
const morgan = require('morgan') ;
const bodyParser = require('body-parser') ;

const productRoutes = require('./api/routes/products') ;
const orderRoutes = require('./api/routes/orders') ;

console.log('abc1') ;

//middleware
app.use(morgan('dev')) ;
app.use(express.urlencoded({ extended: true }));
app.use(express.json);

console.log('abc2') ;

//routes
app.use('/products' , productRoutes ) ;
//console.log('abc5') ;
app.use('/orders' , orderRoutes) ;


//delete it later
app.get('/' , (req , res, next) => {
    res.status(200).json({
        message: 'done'
    }) ;
}) ;
//delete end

//for 404 / not found error
app.use((req,res,next) => {
    const error = new Error('not found');
    error.status = 404 ;
    next(error);
});

//handle any error
app.use((error , req, res,next) => {
    res.status(error.status || 500) ;
    res.json({
        message : error.message 
    }) ;
});

module.exports = app ;

This is my app.js file

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

router.get('/' , (req,res,next) =>{
    console.log('abc') ;
    res.status(200).json({
        message : 'In get routes'
    }
    ) ;
}) ;

router.post('/' , (req,res,next) =>{
    res.status(201).json({
        message : 'In post routes'
    }
    ) ;
}) ;

router.get('/:productId' , (req,res,next) =>{
    res.status(200).json({
        message : 'In get routes' + req.params.productId 
    }
    ) ;
}) ;

module.exports = router ;

This is my products.js file

const http = require('http') ;
const app = require('./app') ;

const port = process.env.PORT || 3000 ;
console.log(port) ;

const server = http.createServer(app);

server.listen(port) ;

This is my server.js file

Upon running the server, everything seems normal and there are no errors being thrown. The console logs are also showing the expected output.

Answer №1

To start, modify your code by:

app.use(bodyParser.json());

Next, ensure you are listening on a specified port. Update your app.js file with the following lines:

const port = 4000;
app.listen(port, () => console.log(`App is now running on port: ${port}!`));

Lastly, include a forward slash in your route declaration:

app.use('/products', productRoutes);

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

Having difficulty adding a custom library from a repository into an Ember project as a dependency

I've been working on a WebGL library that I want to include as a dependency in an EmberJS project. It seems like I should be able to do this directly from the repository without creating an npm package, but I'm running into some issues. To illus ...

Why is the button missing from the codepen?

I attempted to recreate the code from this Codepen link: https://codepen.io/jakaric/pen/mjJQvg However, unlike what you see here (in the run result), the liquid "Pretty little button" is not showing up in my local files. On Codepen, there is no library me ...

Generating a multidimensional associative array based on user inputs from a form

What is the best way to transform form input data into a multidimensional associative array? This is how the form appears: <div id="items"> <h4>Engraving Text</h4> <div class="item" data-position="1"> <h4 id="en ...

Implement error handling middleware when utilizing express.Router

I am looking to implement express.Router in my application. I currently have an index file that serves as the server, and a routes file that defines some express routes using express.Router. My goal is to ensure that whenever one of my routes fails, it tr ...

How come the method $.when().pipe().then() is functioning properly while $.when().then().then() is not working as expected

I'm still grappling with the concept of using JQuery's Deferred objects, and am faced with a puzzling issue. In this code snippet, my attempt to chain deferred.then() was unsuccessful as all three functions executed simultaneously. It wasn't ...

Storing data in a text or HTML file using server-side JavaScript

Currently, I am working on a JavaScript form that involves saving user-entered variables to either a .txt file or a new webpage with the variables pre-filled in the inputs. I know that JavaScript cannot directly manipulate the user's machine, but I am ...

What is the method for downloading a response type document using axios in a front-end application?

As I work on my frontend application, I am faced with the challenge of retrieving files from an API in formats such as docx and odt, and saving them to downloads. In my experimentation using Postman's 'Save response to file' feature, I have ...

Middleware utilized to customize the response configuration

I am looking to enhance my application by creating a middleware that will automatically format the output and return it in a structured format. The desired format is as follows: { "successful": "true", "message": "Successfully created", "data": { ...

Automatically populate select2 dropdown in ASP.NET MVC Core using AJAX

Currently, I am working on a feature to automatically populate text boxes and drop-down fields in my view. To achieve this, I am using a list that I query again. I came across an example that I am referencing here. However, when trying to debug, the break ...

Exploring the capabilities of a Vue.js component

I am currently facing some challenges while trying to test a Vue.js component. My main issue lies in setting a property for the component and verifying that it has been set correctly. For context, the module has been loaded with exports and the JavaScrip ...

Is it possible to transfer a property between components without relying on the props object?

I created a component that showcases a variety of cafes. Inside this component ( CafeList.jsx), an axios request is triggered to fetch a list of cafes, which is then mapped over and displayed on the browser. I envision users being able to click on a spe ...

What is the underlying mechanism behind the functionality of this straightforward node.js proxy?

I am running a frontend-only web application on Netlify that needs to interact with an API on OpenSubtitles.org. Despite the fact that OpenSubtitles.org supports CORS, I sometimes encounter preflight errors, leading me to implement a proxy solution. After ...

What are some ways to create a versatile wrapper?

I'm currently grappling with an issue involving my Formik fields. I need to utilize FastFields in certain scenarios and Fields in others within my FormikControl, a class designed for constructing formik inputs. The challenge lies in being able to swit ...

What is the best way to merge three collections without using $unwind and generate a nested outcome depending on a specific condition?

People Database: [ { "_id": ObjectId("5f3258cfbaaccedaa5dd2c96"), "gender": "male", "name": { "title": "mr", "first": "victor", " ...

What is the process of importing a JSON file in JavaScript?

Is there a way to import a JSON file into my HTML form by calling $(document).ready(function (){});? The properties defined in the JSON file are crucial for the functionality of my form. Can anyone guide me on how to achieve this? ...

Issues with Contenteditable functionality in JavaScript

My goal is to make a row editable when a button is clicked. $(":button").click(function(){ var tdvar=$(this).parent('tr').find('td'); $.each(tdvar,function(){ $(this).prop('contenteditable',true); }); }); <s ...

Navigating to a different intent within the DialogFlow Messenger fulfillment can be done by utilizing the 'agent.setFollowupEvent(targetIntentEventName)' method

I am currently exploring ways to initiate another DialogFlow Intent (using its event) from a webhook server built with node.js. This will occur after gathering the user's email address, verifying their registration status by sending a POST API request ...

The DOM is failing to refresh in Vue.js even after the array has been updated

After receiving a list of items using AJAX, I store them in a data Array: loadSparepartFiles: function() { var vm = this; vm.activeSparepart.attachments = []; ajaxApi.loadJson('spareparts/sparepart/getFiles/'+vm.activeSparepartId, fu ...

display the designated image as a priority

I am designing a loading screen for my website that includes the loading of multiple images, scripts, and other elements. While the HTML and CSS part is working well, I need to ensure that the "loading..." image is loaded before anything else on the page. ...

Attempting to delete a request using FormData resulted in a 500 error response

Currently, I am working on deleting an attachment by sending a request with form data containing a URL through an API path along with an ID. deleteAttachment(id, url) { const formData = new FormData(); formData.append('url', url); ...