The error message that keeps popping up is saying that it cannot access the property "username" as it is undefined

signup.js


const SignupForm = () => {
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");
    

    const handleSignup = () => {
        fetch("/signup", {
            method: "post",
            headers: {
                "Content-Type":"application/json",
                "Accept":"application/json",
            },
            body: JSON.stringify({
                username: username,
                password: password,
            })
        })
        .then(response => response.json())
        .then(data => {
            console.log(data)
        })
    }

    return (
        <div>
            <input type="text" placeholder="username" value={username} onChange={ (e) => setUsername(e.target.value) }/>
            <br/>
            <input type="text" placeholder="password" value={password} onChange={ (e) => setPassword(e.target.value) }/>
            <br/>
            <button id="submit_button" onClick={ () => handleSignup() }>Sign up</button>
        </div>
    )
}

function from auth.js in backend server

router.post("/signup", (request, response) => {
    const username = request.body.username;
    const password = request.body.password;

    // If missing a field: error
    if (!username || !password) {
        response.status(422).json({ error: "Please add all fields" })
    }

    // Checks if there already exists an account with that username
    user.findOne({ username: username })
    .then ((saved_user) => {
        if (saved_user) {
            return response.status(422).json({ error: "There already exists an account with that username"})
        }
    })

    // Creates a new user and saves the account
    const newUser = new User({ username, password })
    newUser.save()
    .then(user => {
        response.json({ message: "Account Saved Successfully"})
    })
    .catch(error => {
        console.log(error)
    })
})

Encountering issue - The json object being posted from signup.js appears to have an undefined body. I've declared username as a constant earlier in the function. Unsure how to resolve this.

Answer №1

Issue resolved by remembering to include App.use(express.json()); at the beginning of routes.

Answer №2

The username and password fields are left empty in the body section

body: JSON.stringify({
                username: "",
                password: "",
            }).
const Signup = () => {
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");    

    const Post = () => {
        fetch("/signup", {
            method: "POST",
            headers: {
                "Content-Type":"application/json",
                "Accept":"application/json",
            },
            body: JSON.stringify({
                username: username,
                password: password,
            })
        })
        .then(response => response.json())
        .then(data => {
            console.log(data)
        })
    }

    return (
        <div>
            <input type="text" placeholder="username" value={username} onChange={ (e) => setUsername(e.target.value) }/>
            <br/>
            <input type="text" placeholder="password" value={password} onChange={ (e) => setPassword(e.target.value) }/>
            <br/>
            <button id="submit_button" onClick={ () => Post() }>Sign up</button>
        </div>
    )
}

You may need to actually enter your username and password for it to work properly.

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

Steps for aligning an image and text within an icon next to each other

I'm looking to align a small PNG image next to some text within an icon. How can I achieve this? Currently, they are stacked vertically. Here is the current layout - I want the two elements side by side instead. The structure of the division is unique ...

Replicate the function of the back button following the submission of an ajax-submitted form to Preview Form

I am currently working on a multi-part form with the following data flow: Complete the form, then SUBMIT (using ajax post) jQuery Form and CodeIgniter validation messages displayed if necessary Preview the submitted answers from the form Options: Canc ...

Convert an object to a custom array using JavaScript

I need to transform the following object: "age": [ { "Under 20": "14", "Above 40": "1" } ] into this structure: $scope data = {rows:[ {c: [ {v: "Under 20"}, {v: 14} ]}, {c: [ {v: "Above 40"}, ...

I am having an issue with my registration form in node.js where it does not redirect after submitting

I am currently working on implementing a registration form using node/express for my website. The routes are all set up and the database connection is established. However, I am encountering some issues when users try to submit the registration form on th ...

Having trouble shutting down Metro Bundler on Windows?

While working on my React Native development, I regularly use npm start to get things going. However, I've run into an issue recently when trying to stop the process using Ctrl + c. It seems like I can no longer use npm start smoothly: ERROR Metro ...

A step-by-step guide to creating a clipboard stream using guacamole-common.js

When utilizing Guacamole.client.createClipboardStream to generate a clipboard stream and sending the stream on paste event, I noticed that the remote clipboard remains empty. const customStream = client.createClipboardStream("text/plain"); cust ...

Adding tween.js seems to have caused the button click event to stop triggering

After adding the code line to tween my display box, the click event is no longer triggered. There are no errors in the console. How can I resolve this issue and what might have caused it? createjs.Tween.get(directionsbox, { loop: false }).to({ x:800, y: ...

What could be causing the props to appear empty in a Child component within a Quasar framework and Vue 3 application?

I am facing an issue while passing props to a Child component table in my Quasar Vue3 app. The content is not being rendered, and I can't figure out why. Strangely, the console is clear of any errors. In the parent component, I am creating an object w ...

An error of type 'TypeError' has occurred, where it is unable to access the property 'render' of an undefined element in

I'm using a function in my controller to render the "result" in my "home-page" view, which is calling my model to execute the query. exports.searchNoms = (req, res) => { getDatabaseModel.searchNoms(req).then(function(result) { console.l ...

The custom confirmation popup is experiencing technical issues

Currently, I am utilizing a plugin to modify the appearance of the confirm popup. Although I have successfully customized the confirm popup, I am encountering an issue where upon clicking the delete icon, the custom confirm popup appears momentarily before ...

The functionality of selecting all items in v-select does not result in saving all of them

I'm currently working on integrating a select all button into the v-select component of Vuetify. The issue I am facing is that even though I can use the button to select all options, when I attempt to save, not all items are saved. However, if I manua ...

Having trouble connecting to Azure SQL server from my Node.js application

I'm attempting to run a basic query to my Azure SQL server from NodeJs, but I'm encountering errors indicating that I cannot establish a connection to the server. The details provided in my code are correct because I've used them successfull ...

A guide on incorporating Vue.js into a Hexo static site generator

Exploring the use of vue.js within my hexo theme has sparked my interest. Can anyone guide me on how to compile my .vue files for both development and production environments? It's worth mentioning that I intend for vue.js to operate on the client sid ...

How to deploy an Express.js application on IIS

Seeking guidance on publishing an express js node application in IIS locally. The resources I've found mention a web.config file, but it's unclear if we should create this ourselves. My project uses express js 4.14.0, handlebars 4.0.1, and tediou ...

How can I use Angular to toggle a submenu based on a data-target attribute when clicked?

Struggling to implement a functionality using ng-click to retrieve the data-target attribute of a clicked angular material md-button, in order to display the submenu when a topic is clicked on the sidenav. The navigation structure consists of md-list with ...

Visualizing Data with Flot.js - A Comprehensive Guide

Does anyone know how to organize values in a flot histogram by day, merging them into one bar per day? I've been searching for a solution but can't seem to find one. __ If you have any ideas, please share! ...

Enable automatic scrolling when a button on the previous page has been clicked

Imagine there are two buttons (Button 1 and Button 2) on a webpage (Page A). Clicking on either button will take you to the same external page (Page B). How can we ensure that Button 1 takes you to the top of Page B, while Button 2 automatically scrolls do ...

Is it possible to exclusively deploy the backend of my React Native app on Heroku?

I am currently developing a react native app with expo, using node.js and Express for the backend. My project structure consists of a frontend folder and a backend (server) folder within the root directory. Root | |Frontend |Various screens & assoc ...

What is the best way to handle multiple JSON data using jQuery?

Understanding how to utilize jquery for parsing simple json is a valuable skill. json { "Symbol": "AAL.L", "Name": "ANGLO AMERICAN", "Last": "3061.50", "Date": "7/26/2011", "Time": "11:35am", "Change": "+3 ...

Modifying iframe src using click event from a separate component in Angular 10

I am looking to dynamically update the src attribute of an iframe when the menu bar is clicked. The menu bar resides in a separate component and includes a dropdown menu for changing languages. Depending on which language is selected, I want to update the ...