Establishing express routing results in API call returning 404 error indicating resource not found

I need some clarification on how to configure my Express routing using app.use and router. My understanding is that I can create a router and then attach it to a route using app.use() to handle all routing related to that route. Can someone assist me in figuring out where my logic may be incorrect? Any help would be greatly appreciated.

Routing

var express = require('express'),
    router = express.Router(),
    mongoose = require('mongoose'),
    PlayingGame = mongoose.model('PlayingGame'),
    FinishedGame = mongoose.model('FinishedGame');

var waiting_user = null;

module.exports = function(app) {
    app.use('/game', router);
};

router.get('/game/waiting', function(req, res, next) {
    if (waiting_user !== null) {
        console.log('Lets put you two in game');
    } else {
        console.log('You need to wait for another player');
    }
});

Client Call

var play = () => {
    var username = username_input.val();

    if (isUsernameValid(username)) {
        $.ajax({
                url: '/game/waiting',
                type: 'GET',
            })
            .done(function() {
                console.log("Success");
            })
            .fail(function() {
                console.log("Error");
            })
            .always(function() {
                console.log("Complete");
            });
    } else {
        alert('Put in a valid username');
    }
};

Answer №1

After reviewing your code, it appears that you have '/game' written twice in the route, resulting in 'baseurl:3000/game/game/waiting'.

If you wish to modify the route, make the following adjustment:

// remove this : router.get('/game/waiting', function(req, res, next) {
router.get('/waiting', function(req, res, next) {
    if (waiting_user !== null) {
        console.log('lets put you two in game');
    } else {
        console.log('you need to wait for another player');
    }
})

Alternatively, if you intend to update the client call, adjust the following code:

var play = () => {
    var username = username_input.val();

    if (isUsernameValid(username)) {
        $.ajax({
                url: '/game/game/waiting',  /* remove this : '/game/waiting', */
                type: 'GET',
            })
            .done(function() {
                console.log("success");
            })
            .fail(function() {
                console.log("error");
            })
            .always(function() {
                console.log("complete");
            });
    } else {
        alert('Put in a valid username');
    }
};

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

How can we store image file paths in MongoDB?

I'm currently working on developing a REST API using nodeJS, express, mongoose, and mongodb. I have successfully implemented file uploads with multer and saved the files to a folder. Now, I need to save the path of the uploaded file to a mongodb docum ...

Express.js does not display console.log messages while routing

Just starting to explore Express and its middleware functions. var express = require('express'); var app = express(); app.get('/', function(req, res) { res.send('id: ' + req.params.id + ' and name: ' + req.param ...

The unexpected behavior in React's reconciliation process: What is causing the state to remain unchanged?

While exploring the React documentation, I came across an interesting example of resetting state: here To better understand it, I created different sandboxes to experiment with. However, I am struggling to reconcile what I observe in each of them. Each s ...

Invoke a JavaScript function once the div has finished loading

After clicking on a radio button, I am dynamically loading a div element. I want to hide a specific part of the div once it is loaded. $(function($) { $('.div_element').on('load', function() { $('.textbox').hide(); } ...

Managing multiple session IDs in ExpressorDealing with dual session

I encountered a situation where: After logging into access.abc.com, I received a cookie named connect.sid with domain as .abc.com Then, on the same browser, I logged into xyz.abc.com and received another session cookie with the same name but a differ ...

Using ng-repeat to iterate over forms in AngularJS

I have implemented dynamic forms using the ng-repeat directive where form fields are generated based on the userid value. The requirement is that the add user button should be enabled only when all form fields are filled. However, currently the button rema ...

Troubleshooting Issue: Failure of Ajax Script to Display Saved Data in Edit Function

Whenever I clicked on the Edit icon in the action column of my data tables, the saved data did not display as expected. I noticed that this issue was only occurring for file input types, while it worked properly for text input types. In the Blade file Ad ...

Streaming with Node/Express does not support downloading files directly using stream.pipe()

Is there a method to trigger a download when I stream data to the response in Node.js? HTTP/1.1 200 OK Server: Cowboy Connection: keep-alive X-Powered-By: Express Content-Type: application/pdf Date: Mon, 10 Oct 2016 20:22:51 GMT Transfer-Encoding: chunked ...

There seems to be an issue with the useReducer value not updating when logging it in a handleSubmit function

I'm currently incorporating useReducer into my Login and Register form. Interestingly, when I attempt to log the reducer value, it only displays the default value. However, if I log it within the useEffect hook, it functions correctly. Below is a sn ...

I'm having trouble retrieving my variable within the socketcluster's socket.on function

How can I store the value of msg in the variable sample when sample is not accessible inside the callback function? import { Injectable } from '@angular/core'; import * as socketCluster from 'socketcluster-client'; @Injectable({ pro ...

Testing Vue with Jest - Unable to test the window.scrollTo function

Is there a way to improve test coverage for a simple scroll to element function using getBoundingClientRect and window.scrollTo? Currently, the Jest tests only provide 100% branch coverage, with all other areas at 0. Function that needs testing: export de ...

Ways to keep selected values in the Select box without unchecking them again?

Hello there, I am relatively new to ReactJS and currently facing an issue with Selects. Specifically, I have a Select component that displays a list of names using MenuItem. My goal is to have certain names pre-selected in the Select dropdown upon initial ...

There seems to be an issue with launching the application using nodemon

Hello everyone! I'm currently working on developing a full stack app, but I've encountered an error that I can't seem to resolve. Even though I've researched the error, I still can't pinpoint where the issue lies. I would greatly ...

Open the CSV document

Why am I receiving an error stating ./vacancy-data.csv cannot be found when attempting to pass the csv file into the csvtojson npm package? The csv file is located in the same directory as the code below: var express = require('express'), route ...

Error: The function .default.auth.signout is not recognized in the REACT and Firebase environment

I've come across several error questions on StackOverflow, but most remain unanswered. The ones that are answered don't seem to solve my issue. I need help debugging this particular error. In my REACT project using Firebase, I'm working on ...

Accessing the SQL database using Cypress

I am attempting to establish a connection with an SQL database using Cypress following the guidelines provided in the NPM guide. I have ensured that all dependencies are installed as specified, however, when I run the following query: cy.sqlServer('S ...

Guide on sending JSON data as a key parameter using res.render()

Hello, I am a beginner with Node.js and I'm currently attempting to send JSON data to index.pug for rendering. The JSON file is located in the root directory, while the index.pug file that receives the data is within a views folder. This JSON data con ...

Obtain and utilize the background color to easily implement the same color in another window

For my Chrome Extension project, I am looking to retrieve the background color of the current page and then set the background color of a window to match. Can someone guide me on how to accomplish this using JavaScript (with or without jQuery), and if ne ...

What is the best way to find all the corners along a path?

I am working with an SVG path and I need to find all the extremum points (corners) on this path. How can I achieve this? I attempted to retrieve all points using the following code: let totalLength = path.getTotalLength(); for (var i = 0; i < totalL ...

What could be the reason for my code showing "success" instead of the intended outcome?

I'm currently working on a project that focuses on verifying whether ingredients are halal or haram. MongoDB is being used to store ingredient information, and express is managing the requests. After sending a GET request to /ingredients/{ingredientn ...