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

What is the best way to swap out particular phrases within HTML documents or specific elements?

Trying to update specific strings within an HTML document or element. How do I go about parsing and replacing them? To clarify: - Identify all instances of #### in element .class - Swap them out with $$$$$ Currently utilizing jQuery for this task. Appre ...

In this JavaScript code, learn how to organize an array based on its numerical property

What is the best way to organize an array based on the 'num' property in this JavaScript array? var data = [{ 005: { `num`: 1360487}, 047: { `num`: 2519472}, 061: { `num`: 1559115}, 081: { `num`: 2232710}, 085: { `num`: 54956 ...

What is the best way to handle texture loading delays in Three.js when using a JSON model?

Currently, I have successfully loaded a JSON model based on AlteredQualia's skinning example. However, I am looking to hide the model until it is fully loaded. In the provided example, the models are displayed before their texture resources finish loa ...

What is the most effective way to transform values into different values using TypeScript?

If I have a list of country codes and I want to display the corresponding country names in my component, how can I achieve this using props? interface MyComponentProps { countryCode: 'en' | 'de' | 'fr'; } const MyComponent: ...

Is there a way to enable popovers globally and also utilize the container: 'body' option simultaneously?

My Bootstrap 5 popovers seem to be missing the arrow and I suspect it's because of interference from the parent element. The documentation provides a solution by using the container: 'body' option on a single item. How can I apply this to al ...

What could be causing my jQuery script to not load properly on the first attempt?

I have a jQuery script set up on this particular webpage just before the ending body tag. Here is the script: <script> $(document).ready(function(){ var demomain = $(".demo-bg section"); var demomainW = demomain.height()+ 150 ...

submit the data to the database

How can I successfully pass the value from the Ajax code to the database in this program aimed at displaying user details? There seems to be an error in the code for passing the value. What steps should I take to rectify this issue? function showUser() ...

Having difficulty in sending emails through Nodemailer using a Google App Password

I implemented a route in an API that involves sending an email to users upon signing up. Utilizing nodemailer and a Google App password, everything was running smoothly until February 3rd, 2023 when the connection suddenly ceased without any changes to the ...

Filter JavaScript elements by conditions and true/false values

I can't quite recall the answer to this at the moment. Consider an array of Vendors (this is just placeholder data): [ { "user_updated": null, "user_created": "128a84b5-275c-4f00-942e-e8ba6d85c60e", "d ...

I prefer to disable the toggle feature if the target remains unchanged

My goal is to create a step-by-step ordering system using the data-id="x" attribute to determine which content should be visible when selected. I want to make sure that if two elements have the same data-id, clicking on one will deselect the other. Any su ...

How to query and sort data using Sequelize's findAll method in a Node

My current issue involves outputting a list of objects from a database using sequelize. I have added an id in the where clause to sort the data, but it doesn't seem to be working as expected. exports.getStaticCompanies = function () { return Comp ...

How can we avoid animations being interrupted by user interaction?

My webpage has an animation that runs smoothly on desktop, but stops as soon as I interact with the page on a touch device. I have tested this issue on Chrome and Safari on iPad. I'm curious if this behavior is intentional on the part of browser vend ...

Select all elements using jQuery that have an id attribute and belong to a specific class

I am attempting to select all items with an ID attribute that starts with a specified string while also having a particular class. For instance, consider the following: <div id="test-id-1" class="test"></div> <div id="test-id-2" class="test ...

Global Day "Sequence" Initiates Subtraction Instead of Preserving Its Authentic Structure

While using Python's Selenium, I am facing a challenge when trying to "inject" an international date string in the specified format into a web page. Unfortunately, instead of getting the expected string, I am getting a result that seems like subtracti ...

The constructor for audio in Next JS cannot be found

I'm facing an issue and struggling to find a solution. My project follows the standard structure of Next JS. In the root directory, I have included a components folder. Within the components folder, there is a component with the following code: imp ...

Can we leverage map/filter/reduce functions within a promise by encapsulating the result with Promise.resolve()?

Currently, my approach to doing loops inside a promise looks like this: asyncFunc() .then(() => { return new Promise((resolve) => { for (let i = 0; i < length; i++) { // do something if (j == length - 1) { ...

Exploring the depths of Mongoose queries with recursive parent references

I'm attempting to replicate the functionality of this MongoDB example using Mongoose, but it seems more complicated in Mongoose. Am I trying to force a square peg into a round hole? This source is taken from http://www.codeproject.com/Articles/521713 ...

I am encountering a 404 error when trying to send a POST request from a React application to an

Utilizing Axios within my react-app. The react app is running on server port 3000 and the express server on port 31001. My react component: import React from 'react'; import {Form,Button} from 'react-bootstrap'; import { Link,useHistor ...

Leveraging the express.static middleware

Both of the code snippets above achieve the same result of serving index.html at localhost:3000/ once the server is up and running. Difference in Approach: express.static const path = require('path'); const express = require('express' ...

Utilizing the change function in conjunction with that

My attempt at creating a simple function to implement the change function didn't go as planned:/ What I am trying to achieve: 1- When a cost checkbox is checked, assign the corresponding cost (e.g., cost1.checked ? cost1 = 10 : 0) 2- Calculate and di ...