error 404 when sending a xhr request in node and react js

I am currently developing a basic login page in React that needs to connect to a database through an AJAX call to a Node.js file.

Here is the Node.js code I have implemented:

var express=require('express');
var app=express();
var db=require('./db');
var bodyParser=require('body-parser');
var server=require('http').Server(app);
app.set('port',process.env.PORT||8080);

app.use(bodyParser.json());

app.set('views','views');
app.set('view engine','html');

app.use(express.static('./public'));

app.use(bodyParser.urlencoded({
    extended:true
}))

app.use(express.json());
app.use(express.urlencoded());

app.post('/newuser',function(req,res){
    console.log(req.body.username);
    console.log(req.body.password);
})

Below is an excerpt of the AJAX call from the React file:

import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import {MusicApp} from './music-app.js';

class Signup extends React.Component{

    constructor(props){
        super(props);
        this.state={
            isLoggedin:false
        }

        this.changePage=this.changePage.bind(this);
    }
    changePage(){

        var username=document.getElementById('username').value;
        var password=document.getElementById('password').value;
        var that=this;
        $.ajax({
            type:'POST',
            url:'/newuser',
            data:{
                username:username,
                password:password
            },
            success:function(){
                that.setState({
                    isLoggedin:true
                })
            }
        })

    }
    render(){
        if(this.state.isLoggedin){
            return(
                <MusicApp/>
                )
        }else{
            return(
                <div>
                <input type='text' id='username' placeholder='username'/>
                <input type='password' id='password' placeholder='password'/>
                <input type='button' id='signup' value='Signup' onClick={this.changePage}/>
                </div>

                )
        }
    }
}

ReactDOM.render(<Signup />,document.getElementById('container'));

index.html

 <!DOCTYPE html>
<html>
<head>
    <title>
        todo-app 
    </title>
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">   
</head>
<body>
    <div id="container"> </div>

    <script type="text/javascript" src="http://localhost:8080/build/vendors.bundle.js"></script>
    <script type="text/javascript" src="http://localhost:8080/build/musicApp.bundle.js"></script> 
</body>
</html>

Upon running the code on port 8080, I encounter a 404 error for xhr request not found. The folder structure of my project can be viewed here. The ajax call originates from signup.js. I have already executed npm install --save express and npm install --save body-parser.

What could possibly be missing in my setup?

Answer №1

It appears that your Express server is not actively listening on any port, even though the port has been set.

Please try implementing the following code:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const db = require('./db');

const PORT = process.env.PORT || 8080;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.set('views', 'views');
app.set('view engine', 'html');

app.use(express.static('./public'));

app.post('/newuser', function(req, res) {
    console.log(req.body.username);
    console.log(req.body.password);
    res.send({postedUserName: req.body.username});
});

if (!module.parent) {
  app.listen(PORT, () => {
    console.log(`Your application starts listening at Port ${PORT}`);
  });
}

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 trouble assigning a default value to an array in the useState declaration

When attempting to set a default value for my state, I encountered an issue where it was returning undefined. However, upon refreshing the page, the values were correctly assigned to categoryIds. const si = [...searchParams.getAll("cat")]; c ...

Utilizing JavaScript and jQuery libraries in conjunction with periods

I am a bit puzzled about when to include the period before referencing class names. For instance, in this code snippet, why is a period included before the first use of the 'active-slide' class but not for the other two instances? var primary = ...

Sort through a list of objects using the criteria from a separate array

Looking to apply a filter on an array of objects: const myArray = [{ id: 4, filters: ["Norway", "Sweden"] }, { id: 2, filters :["Norway", "Sweden"] }, { id: 3, filters:["Denmark", "Sweden&q ...

Can the V8 JavaScript engine made by Google be used on iOS devices?

Is V8 compatible with iOS? If not, what embeddable JavaScript engine would you suggest? UPDATE: We will only be using it for internal scripting purposes, rather than in combination with HTML rendering. ...

What is the appropriate way to retrieve an array that has been stored in the this.state property?

https://i.stack.imgur.com/y9huN.jpgAs a newcomer to react, I have been exploring the react documentation on making Ajax calls. While the docs make it seem simple to retrieve JSON information and set it to a state variable, I've encountered some challe ...

Reset crumbled baked snack via asynchronous JavaScript and XML in PHP made with setcookie function

I recently created a cookie using the setcookie method in PHP. Now, I want to reset this cookie utilizing AJAX but it is not working as expected. If anyone has any insights or ideas on how to accomplish this successfully, your help would be greatly appreci ...

"The error message "Node JS, MYSQL connection.query is not a valid method" indicates

db_config.js: const mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'test' }) connection.connect(function(err) ...

Attempting to integrate a complex Ruby operation (using each loop and iterator) into a JavaScript platform (such as Google Charts API) by creatively combining them in a non-conventional manner during the development phase

It's time for my application to transition into production mode, and I have come to the realization that some of the code in development mode needs a major overhaul. Particularly, the views where I embedded data iteratively into Google Charts API Java ...

What is the process for importing Buffer into a Quasar app that is using Vite as the build tool

I'm having issues with integrating the eth-crypto module into my Quasar app that utilizes Vite. The errors I'm encountering are related to the absence of the Buffer object, which is expected since it's typically found in the front end. Is ...

Using Nuxt.js to import custom NPM packages on a global scale

The installation process for Nuxt's plugins/modules system can be quite intricate. Despite attempting to follow various suggestions, I have struggled to accomplish a seemingly simple task. After installing the NPM package csv-parse (which can be found ...

The error message "TypeError: text is not a function" is displayed when trying to utilize the text() method from either Blob

My current dilemma revolves around the usage of functions defined in the typescript lib.dom.d.ts file within my node.js express backend that is implemented using TypeScript. Specifically, I am encountering issues with the File/Blob interfaces where a File ...

Two separate ajax functions executed sequentially both yield identical results

I am encountering a strange issue with 2 different ajax functions being called consecutively. Each function fetches a different value and populates different text boxes, but they both return the value of the first function called. Here is the code snippet ...

Can't decide between using tabs or back buttons to navigate with react-navigation stack/bottomTab navigator? Here's a step-by

I have developed a unique react native application that currently does not incorporate any form of navigation. However, I am now interested in implementing the powerful functionality offered by react-navigation. Unfortunately, I am encountering difficultie ...

Restrict the Angular ng-repeat directive to specific rows only

Suppose we have a JSON dataset listing all languages of books: $scope.data = [{ "title": "Alice in wonderland", "author": "Lewis Carroll", "lang": ["en"] }, { "title": "Journey to the West", "author": "Wu Cheng'en", "lang": [" ...

Why am I getting a "preflight required for cross-origin requests" error when trying to use Facebook login with Passport?

I'm currently working on a node.js express app that offers RESTful APIs and relies on passport for Facebook authentication. Despite activating all the necessary CORS settings on the server side and successfully consuming APIs through jQuery Ajax, I en ...

Can you identify the issue with the phase control in my sine wave program?

I have recently developed an interactive sine wave drawing web application. Below is the code snippet for reference: const canvas = document.getElementById("canvas"), amplitude_slider = document.getElementById("amplitude_control"), wavelength_slider ...

Are you currently utilizing an unconventional "NODE_ENV" value within your environment settings? Discover how to easily configure the default value of NODE_ENV in a Windows operating system

Recently, I modified the value of NODE_ENV to production using the command: setx NODE_ENV production However, whenever I execute npm run dev or build in my Nextjs project, I encounter an error message saying: You are using a non-standard "NODE_ENV" value ...

Using the hover event in a jQuery plugin: A step-by-step guide

A star rating plugin I am developing is encountering an issue with implementing the hover event. jquery, (function($){ $.fn.extend({ rater: function(options) { var defaults = { } var options = $.exten ...

Module 'swagger_params_parser' is missing and cannot be located

I recently upgraded my Swagger NodeJS project from using swagger-connect 0.1.0 to version 0.7.0 by following the manual instructions. This involved making changes to the default.yml file as shown below: _swagger_params_parser: # <= A ...

Implement jQuery Tabs in Brackets software to enhance user experience

My Adobe Creative Cloud subscription is expiring soon, and I am considering switching to Brackets, an open-source code editor developed by Adobe. However, I am facing some difficulties adding jQuery tabs to my HTML documents. I downloaded the 1.10.4 zip f ...