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

What steps can I take to resolve the issue in my code? I keep receiving a type error stating that it cannot read

I seem to be encountering an issue when running my code where I receive a 'cannot read property 'age' of null'. This error breaks my code, and I'm trying to figure out how to implement a check to ensure it only runs when I am signe ...

Understanding the useQuasar() function in Pinia store file with VueJS

I've encountered an issue in my VueJS + Quasar project where I'm trying to utilize useQuasar() in my store file gallery.js, but it keeps returning undefined. A similar problem arose when I was attempting to access useRouter(), however, I managed ...

Navigating to my own posts within Nuxt: A guide

Having trouble with internal links in my template, as they are not directing to the correct URLs. <nuxt-link :to="blog.url" >{{ blog.title }} by {{ blog.author }}</nuxt-link > In my data, I have the foll ...

Is jQuery's $.trim() function reliable or poorly implemented?

$.trim() utilizes a specific RegExp pattern to trim a string: /^(\s|\u00A0)+|(\s|\u00A0)+$/g However, this can lead to some issues, as demonstrated in the following example: var mystr = ' some test -- more text ...

The ion-input border seems to be fluctuating as the keyboard appears on the screen

I'm currently working with Ionic 3 and experiencing an issue where the selected ion-input's border in the ion-content is shifting when the device keyboard appears on the screen. Here is a visual representation of the problem: https://i.stack.imgu ...

Problem with express-session causing data to not persist between requests

I am working with express-session and attempting to set up a protected route with custom middleware. [DISCLAIMER: At the moment, I am storing my session in-memory] app.use( session({ secret: "f4z4gs$Gcg", cookie: { maxAge: 300000000, s ...

SortTable - Refresh Dropdown Filter in Header After Adding Row to Table

My tablesorter table initially displays two entries in the "License" Filter. If I dynamically add a row, the table now looks like this: I have attempted to update the table using the following commands: $('#connectionGrid2').trigger('upda ...

What is a more efficient approach to managing the response from an asynchronous call other than using setState?

Utilizing javascript async await, I have been making service calls to the server in componentDidMount or componentDidUpdate. However, when I need to pass the response data as props to other components, I find myself updating the component's state with ...

What could be causing the issue with fetch not functioning in my mobile browser?

Recently, I created a basic NodeJS server that stores strings in a database when accessed via "/add", and then sends all those strings to my ReactJS front-end using the endpoint "/getall". The strings are displayed on the front-end using the map function. ...

Ways to maneuver the vehicle by using the left or right key inputs

I am a beginner with canvas and game development. I am currently working on a project where a car moves in a straight line, but I want to add functionality for the car to turn anti-clockwise when the left key is pressed, and clockwise when the right key is ...

Guide on submitting a form in ReactJS with Material UI Dialog

I utilized the Material UI Dialog to create a form list. In the official example: <Dialog title="Dialog With Custom Width" actions={actions} modal={true} open={this.state.open} > This dialog ...

Utilizing Angular's ngRoute Module in Conjunction with Node.js

I'm currently working on implementing AngularJS routes with my NodeJS http server. Here is the code I have: server.js: app.set('port', 3000); app.use(express.static(__dirname)); app.use(bodyParser.urlencoded({ extended: false })); app.use( ...

Having trouble with downloading a node module?

I encountered an issue while trying to download the node-sass node module. The error message I received was as follows: To download the node-sass module, use the command: npm install --save-dev node-sass Error Binary has a problem: Error: \?\C: ...

Have Apache route all incoming requests for a particular domain directly to an Express server

I must admit, I am not an Apache expert nor a novice when it comes to Apache. My current setup involves an express server listening on port 443 hosted on a VPS running Centos7 that also hosts around 40 other websites using Apache (configured using cPanel a ...

Getting an error that reads, "Unable to read properties of null (reading 'uid')," but surprisingly, the application continues to function properly

After logging out, I encounter the following error: (Uncaught TypeError: Cannot read properties of null (reading 'uid')). However, my application functions as intended. During the logout process, I delete an API access token from the user docume ...

Is there a way to update a child component in React when the parent state changes, without utilizing the componentWill

I am currently working on developing a JSON editor using React, but I am facing an issue with the library I am utilizing not having a componentWillReceiveProps hook. As someone relatively new to React, I am trying to find a way to automatically update th ...

Getting URL parameters dynamically without reloading the page

Here's a particular issue I'm encountering: I've implemented the following function to fetch the GET Parameters from a URL. $(document).ready(function() { function getParam(variable) { var query = window.location.search.sub ...

JavaScript does not reflect updates made to the ASP.Net session

After clicking the button, I trigger the JavaScript to retrieve the session information. However, I am encountering an issue where the value of the session is not being updated. alert('<%= Session["file"]%>'); ...

Steps for integrating a valid SSL certificate into a Reactjs application

After completing my ReactJS app for my website, I am now ready to launch it in production mode. The only hurdle I face is getting it to work under https mode. This app was developed using create-react-app in a local environment and has since been deployed ...

Building Silent Authentication in React Native with the help of Auth0: A Step-by-Step Guide

I am currently working on my first React Native app, and I have integrated Auth0 for authentication purposes. My goal is to implement silent authentication using refresh tokens. So far, I have attempted to use the checkSession() method but encountered an ...