Can't post data to Express using React











up vote
0
down vote

favorite












This is my first time trying to make a full stack app. I already have experience with Django but now i wanted to try using Express.js
So, i made this simple route in express:



var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var logger = require('morgan');

var User = require('../User/User');


app.use(logger("short"));

app.post("/addUser", (req, res) => {
User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password
}, (err, user) => {
if (err) return res.status(500).json({auth: false})
res.status(200).json(
{
email,
name
}
);
});
});


this is the User schema:



const mongoose = require("mongoose")
const Schema = mongoose.Schema;

const UserSchema = new Schema(
{
name: String,
email: String,
password: String,
},
{timestamps: true}
);
mongoose.model("User", UserSchema);

module.exports = mongoose.model("User");


I already tried doing some post requests using insomnia. They all worked
But when i make a post request using react it creates an object but its name, email, password fields are empty, like this:



createdAt: "2018-11-22T16:59:51.844Z"
updatedAt: "2018-11-22T16:59:51.844Z"
__v: 0
_id: "5bf6e0878bd6663807e57dec"


this is my react code - it's in a func that's called when the form is submitted - (I already added the express server as a proxy):



    axios.post('/api/auth/addUser', {
name: register_name,
email: register_email,
password: register_password
})
.then(res => res.json())
.catch(err => console.log(err))


I get code 200 on express' console but the obj doesn't have any data.
Can you help me? - I'm still a beginner to React and Express



Edit: React Component



import React, { Component } from 'react';
import axios from 'axios';

export default class Register extends Component {
constructor(props) {
super(props)
this.state = {
register_name: "",
register_email: "",
register_password: ""
}

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);

}

handleChange(event) {
this.setState({[event.target.name]: event.target.value})
}

handleSubmit(event) {
event.preventDefault();
const { register_name, register_email, register_password } = this.state
axios.post('/api/auth/addUser', {
name: register_name,
email: register_email,
password: register_password
})
.then(res => res.json())
.catch(err => console.log(err))

console.log(this.state)

this.clearInputs();

}

render() {
return (
<div>
<form method={"POST"} onSubmit={this.handleSubmit} id={"register-form"}>
<label htmlFor={"register_name"}></label>
<input type={"text"} name={"register_name"} id={"register_name"} placeholder={"name"} value={this.state.register_name} onChange={this.handleChange}></input>
<label htmlFor={"register_email"}>Email</label>
<input type={"email"} name={"register_email"} id={"register_email"} placeholder={"email"} value={this.state.register_email} onChange={this.handleChange}></input>
<label htmlFor={"register_password"} >Password</label>
<input type={"password"} name={"register_password"} id={"register_password"} placeholder={"password"} value={this.state.register_password} onChange={this.handleChange}></input>
<button type={"submit"}>Submit</button>
</form>
</div>
)
}


}










share|improve this question
























  • any console entries? maybe a CORS issue?
    – luschn
    Nov 22 at 17:22










  • You are taking the info to submit from the state of the component name: this.state.name etc, are you sure it is correctly populated ? Show the code of that component.
    – Gabriele Petrioli
    Nov 22 at 17:22












  • Just added the code of the component
    – Abel Hristodor
    Nov 22 at 17:34















up vote
0
down vote

favorite












This is my first time trying to make a full stack app. I already have experience with Django but now i wanted to try using Express.js
So, i made this simple route in express:



var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var logger = require('morgan');

var User = require('../User/User');


app.use(logger("short"));

app.post("/addUser", (req, res) => {
User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password
}, (err, user) => {
if (err) return res.status(500).json({auth: false})
res.status(200).json(
{
email,
name
}
);
});
});


this is the User schema:



const mongoose = require("mongoose")
const Schema = mongoose.Schema;

const UserSchema = new Schema(
{
name: String,
email: String,
password: String,
},
{timestamps: true}
);
mongoose.model("User", UserSchema);

module.exports = mongoose.model("User");


I already tried doing some post requests using insomnia. They all worked
But when i make a post request using react it creates an object but its name, email, password fields are empty, like this:



createdAt: "2018-11-22T16:59:51.844Z"
updatedAt: "2018-11-22T16:59:51.844Z"
__v: 0
_id: "5bf6e0878bd6663807e57dec"


this is my react code - it's in a func that's called when the form is submitted - (I already added the express server as a proxy):



    axios.post('/api/auth/addUser', {
name: register_name,
email: register_email,
password: register_password
})
.then(res => res.json())
.catch(err => console.log(err))


I get code 200 on express' console but the obj doesn't have any data.
Can you help me? - I'm still a beginner to React and Express



Edit: React Component



import React, { Component } from 'react';
import axios from 'axios';

export default class Register extends Component {
constructor(props) {
super(props)
this.state = {
register_name: "",
register_email: "",
register_password: ""
}

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);

}

handleChange(event) {
this.setState({[event.target.name]: event.target.value})
}

handleSubmit(event) {
event.preventDefault();
const { register_name, register_email, register_password } = this.state
axios.post('/api/auth/addUser', {
name: register_name,
email: register_email,
password: register_password
})
.then(res => res.json())
.catch(err => console.log(err))

console.log(this.state)

this.clearInputs();

}

render() {
return (
<div>
<form method={"POST"} onSubmit={this.handleSubmit} id={"register-form"}>
<label htmlFor={"register_name"}></label>
<input type={"text"} name={"register_name"} id={"register_name"} placeholder={"name"} value={this.state.register_name} onChange={this.handleChange}></input>
<label htmlFor={"register_email"}>Email</label>
<input type={"email"} name={"register_email"} id={"register_email"} placeholder={"email"} value={this.state.register_email} onChange={this.handleChange}></input>
<label htmlFor={"register_password"} >Password</label>
<input type={"password"} name={"register_password"} id={"register_password"} placeholder={"password"} value={this.state.register_password} onChange={this.handleChange}></input>
<button type={"submit"}>Submit</button>
</form>
</div>
)
}


}










share|improve this question
























  • any console entries? maybe a CORS issue?
    – luschn
    Nov 22 at 17:22










  • You are taking the info to submit from the state of the component name: this.state.name etc, are you sure it is correctly populated ? Show the code of that component.
    – Gabriele Petrioli
    Nov 22 at 17:22












  • Just added the code of the component
    – Abel Hristodor
    Nov 22 at 17:34













up vote
0
down vote

favorite









up vote
0
down vote

favorite











This is my first time trying to make a full stack app. I already have experience with Django but now i wanted to try using Express.js
So, i made this simple route in express:



var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var logger = require('morgan');

var User = require('../User/User');


app.use(logger("short"));

app.post("/addUser", (req, res) => {
User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password
}, (err, user) => {
if (err) return res.status(500).json({auth: false})
res.status(200).json(
{
email,
name
}
);
});
});


this is the User schema:



const mongoose = require("mongoose")
const Schema = mongoose.Schema;

const UserSchema = new Schema(
{
name: String,
email: String,
password: String,
},
{timestamps: true}
);
mongoose.model("User", UserSchema);

module.exports = mongoose.model("User");


I already tried doing some post requests using insomnia. They all worked
But when i make a post request using react it creates an object but its name, email, password fields are empty, like this:



createdAt: "2018-11-22T16:59:51.844Z"
updatedAt: "2018-11-22T16:59:51.844Z"
__v: 0
_id: "5bf6e0878bd6663807e57dec"


this is my react code - it's in a func that's called when the form is submitted - (I already added the express server as a proxy):



    axios.post('/api/auth/addUser', {
name: register_name,
email: register_email,
password: register_password
})
.then(res => res.json())
.catch(err => console.log(err))


I get code 200 on express' console but the obj doesn't have any data.
Can you help me? - I'm still a beginner to React and Express



Edit: React Component



import React, { Component } from 'react';
import axios from 'axios';

export default class Register extends Component {
constructor(props) {
super(props)
this.state = {
register_name: "",
register_email: "",
register_password: ""
}

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);

}

handleChange(event) {
this.setState({[event.target.name]: event.target.value})
}

handleSubmit(event) {
event.preventDefault();
const { register_name, register_email, register_password } = this.state
axios.post('/api/auth/addUser', {
name: register_name,
email: register_email,
password: register_password
})
.then(res => res.json())
.catch(err => console.log(err))

console.log(this.state)

this.clearInputs();

}

render() {
return (
<div>
<form method={"POST"} onSubmit={this.handleSubmit} id={"register-form"}>
<label htmlFor={"register_name"}></label>
<input type={"text"} name={"register_name"} id={"register_name"} placeholder={"name"} value={this.state.register_name} onChange={this.handleChange}></input>
<label htmlFor={"register_email"}>Email</label>
<input type={"email"} name={"register_email"} id={"register_email"} placeholder={"email"} value={this.state.register_email} onChange={this.handleChange}></input>
<label htmlFor={"register_password"} >Password</label>
<input type={"password"} name={"register_password"} id={"register_password"} placeholder={"password"} value={this.state.register_password} onChange={this.handleChange}></input>
<button type={"submit"}>Submit</button>
</form>
</div>
)
}


}










share|improve this question















This is my first time trying to make a full stack app. I already have experience with Django but now i wanted to try using Express.js
So, i made this simple route in express:



var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var logger = require('morgan');

var User = require('../User/User');


app.use(logger("short"));

app.post("/addUser", (req, res) => {
User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password
}, (err, user) => {
if (err) return res.status(500).json({auth: false})
res.status(200).json(
{
email,
name
}
);
});
});


this is the User schema:



const mongoose = require("mongoose")
const Schema = mongoose.Schema;

const UserSchema = new Schema(
{
name: String,
email: String,
password: String,
},
{timestamps: true}
);
mongoose.model("User", UserSchema);

module.exports = mongoose.model("User");


I already tried doing some post requests using insomnia. They all worked
But when i make a post request using react it creates an object but its name, email, password fields are empty, like this:



createdAt: "2018-11-22T16:59:51.844Z"
updatedAt: "2018-11-22T16:59:51.844Z"
__v: 0
_id: "5bf6e0878bd6663807e57dec"


this is my react code - it's in a func that's called when the form is submitted - (I already added the express server as a proxy):



    axios.post('/api/auth/addUser', {
name: register_name,
email: register_email,
password: register_password
})
.then(res => res.json())
.catch(err => console.log(err))


I get code 200 on express' console but the obj doesn't have any data.
Can you help me? - I'm still a beginner to React and Express



Edit: React Component



import React, { Component } from 'react';
import axios from 'axios';

export default class Register extends Component {
constructor(props) {
super(props)
this.state = {
register_name: "",
register_email: "",
register_password: ""
}

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);

}

handleChange(event) {
this.setState({[event.target.name]: event.target.value})
}

handleSubmit(event) {
event.preventDefault();
const { register_name, register_email, register_password } = this.state
axios.post('/api/auth/addUser', {
name: register_name,
email: register_email,
password: register_password
})
.then(res => res.json())
.catch(err => console.log(err))

console.log(this.state)

this.clearInputs();

}

render() {
return (
<div>
<form method={"POST"} onSubmit={this.handleSubmit} id={"register-form"}>
<label htmlFor={"register_name"}></label>
<input type={"text"} name={"register_name"} id={"register_name"} placeholder={"name"} value={this.state.register_name} onChange={this.handleChange}></input>
<label htmlFor={"register_email"}>Email</label>
<input type={"email"} name={"register_email"} id={"register_email"} placeholder={"email"} value={this.state.register_email} onChange={this.handleChange}></input>
<label htmlFor={"register_password"} >Password</label>
<input type={"password"} name={"register_password"} id={"register_password"} placeholder={"password"} value={this.state.register_password} onChange={this.handleChange}></input>
<button type={"submit"}>Submit</button>
</form>
</div>
)
}


}







javascript reactjs express axios






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 at 18:59

























asked Nov 22 at 17:16









Abel Hristodor

125




125












  • any console entries? maybe a CORS issue?
    – luschn
    Nov 22 at 17:22










  • You are taking the info to submit from the state of the component name: this.state.name etc, are you sure it is correctly populated ? Show the code of that component.
    – Gabriele Petrioli
    Nov 22 at 17:22












  • Just added the code of the component
    – Abel Hristodor
    Nov 22 at 17:34


















  • any console entries? maybe a CORS issue?
    – luschn
    Nov 22 at 17:22










  • You are taking the info to submit from the state of the component name: this.state.name etc, are you sure it is correctly populated ? Show the code of that component.
    – Gabriele Petrioli
    Nov 22 at 17:22












  • Just added the code of the component
    – Abel Hristodor
    Nov 22 at 17:34
















any console entries? maybe a CORS issue?
– luschn
Nov 22 at 17:22




any console entries? maybe a CORS issue?
– luschn
Nov 22 at 17:22












You are taking the info to submit from the state of the component name: this.state.name etc, are you sure it is correctly populated ? Show the code of that component.
– Gabriele Petrioli
Nov 22 at 17:22






You are taking the info to submit from the state of the component name: this.state.name etc, are you sure it is correctly populated ? Show the code of that component.
– Gabriele Petrioli
Nov 22 at 17:22














Just added the code of the component
– Abel Hristodor
Nov 22 at 17:34




Just added the code of the component
– Abel Hristodor
Nov 22 at 17:34












3 Answers
3






active

oldest

votes

















up vote
0
down vote



accepted










There's a series of potential problems here. First, there's no particular need to make a urlencoded form submission here: just use JSON. Your submit could then look something like:



handleSubmit (e) {
e.preventDefault()
const { email, name, password } = this.state
axios.post('/api/auth/adduser', {
email,
name,
password
})
.then(res => /* ... */)
.catch(err => /* ... */)
}


On the server, you're probably after res.json rather than res.send.



const { email, name, password } = req.body
// ...
res.status(201).json({
email,
name
})


Also note that you don't need bodyParser these days (you can just use express.json()).



Finally, you should use event.target.name in your handleChange as the names match the names of your values in component state:



handleChange (e) {
this.setState({ [e.target.name]: event.target.value })
}


Simple example



Client:



const CLEAR_STATE = {
email: '',
name: '',
password: '',
message: ''
}

export default class App extends Component {
state = CLEAR_STATE

handleChange = e => this.setState({
[ e.target.name ]: e.target.value
})

handleSubmit = e => {
e.preventDefault()
const { email, name, password } = this.state
axios.post('/', { email, name, password })
.then(({ data }) => this.setState({
...CLEAR_STATE,
message: `You sent: ${data.email}, ${data.name}, ${data.password}.`
}))
.catch(({ message }) => this.setState({ message }))
}

render () {
return (
<>
<form onSubmit={this.handleSubmit}>
<input
type='text'
name='email'
value={this.state.email}
onChange={this.handleChange} />
<input
type='text'
name='name'
value={this.state.name}
onChange={this.handleChange} />
<input
type='password'
name='password'
value={this.state.password}
onChange={this.handleChange} />
<input type='submit' value='Register' />
</form>
{this.state.message && <p>{this.state.message}</p>}
</>
)
}
}


Server:



app.use(express.json())

app.post('/', (req, res) => {
const { name, email, password } = req.body
res.status(201).json({ name, email, password })
})





share|improve this answer























  • Ok, changed everything but now i get status code 500 -Cannot read property 'register_name' of undefined ( i changed all the names to register_name ecc)
    – Abel Hristodor
    Nov 22 at 18:05












  • handleSubmit(event) { event.preventDefault(); const { register_name, register_email, register_password } = this.state axios.post('/api/auth/addUser', { name: register_name, email: register_email, password: register_password }) .then(res => res.json()) .catch(err => console.log(err)) console.log(this.state) this.clearInputs(); } This is the handler
    – Abel Hristodor
    Nov 22 at 18:06










  • You appear to have skipped adding app.use(express.json()) in your server-side code. This is why your req.body is undefined.
    – Rich Churcher
    Nov 22 at 19:02








  • 1




    Oh haha thanks :)
    – Abel Hristodor
    Nov 22 at 19:26


















up vote
1
down vote













You are using the [event.target.id] of the changed input element to update the state.



You state expects name,email,password but receives register_name,register_email,register_password.



You should change the id of the input elements to match those in the state or you should use the name attribute since that is what matches .



this.setState({[event.target.name]: event.target.value});




Keep in mind that the attribute htmlFor of the label elements also needs to match the id and not the name of the element it is linked to.





Also, you should have noticed that something was wrong since your code will not update the input elements while you type.






share|improve this answer





















  • oh yeah, forgot i changed them haha. Anyway, changed everything, same result
    – Abel Hristodor
    Nov 22 at 17:49










  • @AbelHristodor again you name the post parameters name, email,password in the axios call, but in your server route you are using req.body.register_name to access them.
    – Gabriele Petrioli
    Nov 22 at 18:54












  • okk, but now i get ` Cannot read property 'name' of undefined```
    – Abel Hristodor
    Nov 22 at 18:59










  • @AbelHristodor you need app.use(express.json()); in your server side script.
    – Gabriele Petrioli
    Nov 22 at 19:08










  • Okk thanks :) I've been trying to solve this problem for a few days and it got very frustrating haha
    – Abel Hristodor
    Nov 22 at 19:25


















up vote
0
down vote













Everything works out of the box with just bare fetch.
Here is gist, just make sure you attached bodyParser to express instance



const bodyParser = require('body-parser');
...
app.use(bodyParser.json());


axios lib is useful if you want to upload physical files with FormData






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53435712%2fcant-post-data-to-express-using-react%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    There's a series of potential problems here. First, there's no particular need to make a urlencoded form submission here: just use JSON. Your submit could then look something like:



    handleSubmit (e) {
    e.preventDefault()
    const { email, name, password } = this.state
    axios.post('/api/auth/adduser', {
    email,
    name,
    password
    })
    .then(res => /* ... */)
    .catch(err => /* ... */)
    }


    On the server, you're probably after res.json rather than res.send.



    const { email, name, password } = req.body
    // ...
    res.status(201).json({
    email,
    name
    })


    Also note that you don't need bodyParser these days (you can just use express.json()).



    Finally, you should use event.target.name in your handleChange as the names match the names of your values in component state:



    handleChange (e) {
    this.setState({ [e.target.name]: event.target.value })
    }


    Simple example



    Client:



    const CLEAR_STATE = {
    email: '',
    name: '',
    password: '',
    message: ''
    }

    export default class App extends Component {
    state = CLEAR_STATE

    handleChange = e => this.setState({
    [ e.target.name ]: e.target.value
    })

    handleSubmit = e => {
    e.preventDefault()
    const { email, name, password } = this.state
    axios.post('/', { email, name, password })
    .then(({ data }) => this.setState({
    ...CLEAR_STATE,
    message: `You sent: ${data.email}, ${data.name}, ${data.password}.`
    }))
    .catch(({ message }) => this.setState({ message }))
    }

    render () {
    return (
    <>
    <form onSubmit={this.handleSubmit}>
    <input
    type='text'
    name='email'
    value={this.state.email}
    onChange={this.handleChange} />
    <input
    type='text'
    name='name'
    value={this.state.name}
    onChange={this.handleChange} />
    <input
    type='password'
    name='password'
    value={this.state.password}
    onChange={this.handleChange} />
    <input type='submit' value='Register' />
    </form>
    {this.state.message && <p>{this.state.message}</p>}
    </>
    )
    }
    }


    Server:



    app.use(express.json())

    app.post('/', (req, res) => {
    const { name, email, password } = req.body
    res.status(201).json({ name, email, password })
    })





    share|improve this answer























    • Ok, changed everything but now i get status code 500 -Cannot read property 'register_name' of undefined ( i changed all the names to register_name ecc)
      – Abel Hristodor
      Nov 22 at 18:05












    • handleSubmit(event) { event.preventDefault(); const { register_name, register_email, register_password } = this.state axios.post('/api/auth/addUser', { name: register_name, email: register_email, password: register_password }) .then(res => res.json()) .catch(err => console.log(err)) console.log(this.state) this.clearInputs(); } This is the handler
      – Abel Hristodor
      Nov 22 at 18:06










    • You appear to have skipped adding app.use(express.json()) in your server-side code. This is why your req.body is undefined.
      – Rich Churcher
      Nov 22 at 19:02








    • 1




      Oh haha thanks :)
      – Abel Hristodor
      Nov 22 at 19:26















    up vote
    0
    down vote



    accepted










    There's a series of potential problems here. First, there's no particular need to make a urlencoded form submission here: just use JSON. Your submit could then look something like:



    handleSubmit (e) {
    e.preventDefault()
    const { email, name, password } = this.state
    axios.post('/api/auth/adduser', {
    email,
    name,
    password
    })
    .then(res => /* ... */)
    .catch(err => /* ... */)
    }


    On the server, you're probably after res.json rather than res.send.



    const { email, name, password } = req.body
    // ...
    res.status(201).json({
    email,
    name
    })


    Also note that you don't need bodyParser these days (you can just use express.json()).



    Finally, you should use event.target.name in your handleChange as the names match the names of your values in component state:



    handleChange (e) {
    this.setState({ [e.target.name]: event.target.value })
    }


    Simple example



    Client:



    const CLEAR_STATE = {
    email: '',
    name: '',
    password: '',
    message: ''
    }

    export default class App extends Component {
    state = CLEAR_STATE

    handleChange = e => this.setState({
    [ e.target.name ]: e.target.value
    })

    handleSubmit = e => {
    e.preventDefault()
    const { email, name, password } = this.state
    axios.post('/', { email, name, password })
    .then(({ data }) => this.setState({
    ...CLEAR_STATE,
    message: `You sent: ${data.email}, ${data.name}, ${data.password}.`
    }))
    .catch(({ message }) => this.setState({ message }))
    }

    render () {
    return (
    <>
    <form onSubmit={this.handleSubmit}>
    <input
    type='text'
    name='email'
    value={this.state.email}
    onChange={this.handleChange} />
    <input
    type='text'
    name='name'
    value={this.state.name}
    onChange={this.handleChange} />
    <input
    type='password'
    name='password'
    value={this.state.password}
    onChange={this.handleChange} />
    <input type='submit' value='Register' />
    </form>
    {this.state.message && <p>{this.state.message}</p>}
    </>
    )
    }
    }


    Server:



    app.use(express.json())

    app.post('/', (req, res) => {
    const { name, email, password } = req.body
    res.status(201).json({ name, email, password })
    })





    share|improve this answer























    • Ok, changed everything but now i get status code 500 -Cannot read property 'register_name' of undefined ( i changed all the names to register_name ecc)
      – Abel Hristodor
      Nov 22 at 18:05












    • handleSubmit(event) { event.preventDefault(); const { register_name, register_email, register_password } = this.state axios.post('/api/auth/addUser', { name: register_name, email: register_email, password: register_password }) .then(res => res.json()) .catch(err => console.log(err)) console.log(this.state) this.clearInputs(); } This is the handler
      – Abel Hristodor
      Nov 22 at 18:06










    • You appear to have skipped adding app.use(express.json()) in your server-side code. This is why your req.body is undefined.
      – Rich Churcher
      Nov 22 at 19:02








    • 1




      Oh haha thanks :)
      – Abel Hristodor
      Nov 22 at 19:26













    up vote
    0
    down vote



    accepted







    up vote
    0
    down vote



    accepted






    There's a series of potential problems here. First, there's no particular need to make a urlencoded form submission here: just use JSON. Your submit could then look something like:



    handleSubmit (e) {
    e.preventDefault()
    const { email, name, password } = this.state
    axios.post('/api/auth/adduser', {
    email,
    name,
    password
    })
    .then(res => /* ... */)
    .catch(err => /* ... */)
    }


    On the server, you're probably after res.json rather than res.send.



    const { email, name, password } = req.body
    // ...
    res.status(201).json({
    email,
    name
    })


    Also note that you don't need bodyParser these days (you can just use express.json()).



    Finally, you should use event.target.name in your handleChange as the names match the names of your values in component state:



    handleChange (e) {
    this.setState({ [e.target.name]: event.target.value })
    }


    Simple example



    Client:



    const CLEAR_STATE = {
    email: '',
    name: '',
    password: '',
    message: ''
    }

    export default class App extends Component {
    state = CLEAR_STATE

    handleChange = e => this.setState({
    [ e.target.name ]: e.target.value
    })

    handleSubmit = e => {
    e.preventDefault()
    const { email, name, password } = this.state
    axios.post('/', { email, name, password })
    .then(({ data }) => this.setState({
    ...CLEAR_STATE,
    message: `You sent: ${data.email}, ${data.name}, ${data.password}.`
    }))
    .catch(({ message }) => this.setState({ message }))
    }

    render () {
    return (
    <>
    <form onSubmit={this.handleSubmit}>
    <input
    type='text'
    name='email'
    value={this.state.email}
    onChange={this.handleChange} />
    <input
    type='text'
    name='name'
    value={this.state.name}
    onChange={this.handleChange} />
    <input
    type='password'
    name='password'
    value={this.state.password}
    onChange={this.handleChange} />
    <input type='submit' value='Register' />
    </form>
    {this.state.message && <p>{this.state.message}</p>}
    </>
    )
    }
    }


    Server:



    app.use(express.json())

    app.post('/', (req, res) => {
    const { name, email, password } = req.body
    res.status(201).json({ name, email, password })
    })





    share|improve this answer














    There's a series of potential problems here. First, there's no particular need to make a urlencoded form submission here: just use JSON. Your submit could then look something like:



    handleSubmit (e) {
    e.preventDefault()
    const { email, name, password } = this.state
    axios.post('/api/auth/adduser', {
    email,
    name,
    password
    })
    .then(res => /* ... */)
    .catch(err => /* ... */)
    }


    On the server, you're probably after res.json rather than res.send.



    const { email, name, password } = req.body
    // ...
    res.status(201).json({
    email,
    name
    })


    Also note that you don't need bodyParser these days (you can just use express.json()).



    Finally, you should use event.target.name in your handleChange as the names match the names of your values in component state:



    handleChange (e) {
    this.setState({ [e.target.name]: event.target.value })
    }


    Simple example



    Client:



    const CLEAR_STATE = {
    email: '',
    name: '',
    password: '',
    message: ''
    }

    export default class App extends Component {
    state = CLEAR_STATE

    handleChange = e => this.setState({
    [ e.target.name ]: e.target.value
    })

    handleSubmit = e => {
    e.preventDefault()
    const { email, name, password } = this.state
    axios.post('/', { email, name, password })
    .then(({ data }) => this.setState({
    ...CLEAR_STATE,
    message: `You sent: ${data.email}, ${data.name}, ${data.password}.`
    }))
    .catch(({ message }) => this.setState({ message }))
    }

    render () {
    return (
    <>
    <form onSubmit={this.handleSubmit}>
    <input
    type='text'
    name='email'
    value={this.state.email}
    onChange={this.handleChange} />
    <input
    type='text'
    name='name'
    value={this.state.name}
    onChange={this.handleChange} />
    <input
    type='password'
    name='password'
    value={this.state.password}
    onChange={this.handleChange} />
    <input type='submit' value='Register' />
    </form>
    {this.state.message && <p>{this.state.message}</p>}
    </>
    )
    }
    }


    Server:



    app.use(express.json())

    app.post('/', (req, res) => {
    const { name, email, password } = req.body
    res.status(201).json({ name, email, password })
    })






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 22 at 20:01

























    answered Nov 22 at 17:48









    Rich Churcher

    2,53322343




    2,53322343












    • Ok, changed everything but now i get status code 500 -Cannot read property 'register_name' of undefined ( i changed all the names to register_name ecc)
      – Abel Hristodor
      Nov 22 at 18:05












    • handleSubmit(event) { event.preventDefault(); const { register_name, register_email, register_password } = this.state axios.post('/api/auth/addUser', { name: register_name, email: register_email, password: register_password }) .then(res => res.json()) .catch(err => console.log(err)) console.log(this.state) this.clearInputs(); } This is the handler
      – Abel Hristodor
      Nov 22 at 18:06










    • You appear to have skipped adding app.use(express.json()) in your server-side code. This is why your req.body is undefined.
      – Rich Churcher
      Nov 22 at 19:02








    • 1




      Oh haha thanks :)
      – Abel Hristodor
      Nov 22 at 19:26


















    • Ok, changed everything but now i get status code 500 -Cannot read property 'register_name' of undefined ( i changed all the names to register_name ecc)
      – Abel Hristodor
      Nov 22 at 18:05












    • handleSubmit(event) { event.preventDefault(); const { register_name, register_email, register_password } = this.state axios.post('/api/auth/addUser', { name: register_name, email: register_email, password: register_password }) .then(res => res.json()) .catch(err => console.log(err)) console.log(this.state) this.clearInputs(); } This is the handler
      – Abel Hristodor
      Nov 22 at 18:06










    • You appear to have skipped adding app.use(express.json()) in your server-side code. This is why your req.body is undefined.
      – Rich Churcher
      Nov 22 at 19:02








    • 1




      Oh haha thanks :)
      – Abel Hristodor
      Nov 22 at 19:26
















    Ok, changed everything but now i get status code 500 -Cannot read property 'register_name' of undefined ( i changed all the names to register_name ecc)
    – Abel Hristodor
    Nov 22 at 18:05






    Ok, changed everything but now i get status code 500 -Cannot read property 'register_name' of undefined ( i changed all the names to register_name ecc)
    – Abel Hristodor
    Nov 22 at 18:05














    handleSubmit(event) { event.preventDefault(); const { register_name, register_email, register_password } = this.state axios.post('/api/auth/addUser', { name: register_name, email: register_email, password: register_password }) .then(res => res.json()) .catch(err => console.log(err)) console.log(this.state) this.clearInputs(); } This is the handler
    – Abel Hristodor
    Nov 22 at 18:06




    handleSubmit(event) { event.preventDefault(); const { register_name, register_email, register_password } = this.state axios.post('/api/auth/addUser', { name: register_name, email: register_email, password: register_password }) .then(res => res.json()) .catch(err => console.log(err)) console.log(this.state) this.clearInputs(); } This is the handler
    – Abel Hristodor
    Nov 22 at 18:06












    You appear to have skipped adding app.use(express.json()) in your server-side code. This is why your req.body is undefined.
    – Rich Churcher
    Nov 22 at 19:02






    You appear to have skipped adding app.use(express.json()) in your server-side code. This is why your req.body is undefined.
    – Rich Churcher
    Nov 22 at 19:02






    1




    1




    Oh haha thanks :)
    – Abel Hristodor
    Nov 22 at 19:26




    Oh haha thanks :)
    – Abel Hristodor
    Nov 22 at 19:26












    up vote
    1
    down vote













    You are using the [event.target.id] of the changed input element to update the state.



    You state expects name,email,password but receives register_name,register_email,register_password.



    You should change the id of the input elements to match those in the state or you should use the name attribute since that is what matches .



    this.setState({[event.target.name]: event.target.value});




    Keep in mind that the attribute htmlFor of the label elements also needs to match the id and not the name of the element it is linked to.





    Also, you should have noticed that something was wrong since your code will not update the input elements while you type.






    share|improve this answer





















    • oh yeah, forgot i changed them haha. Anyway, changed everything, same result
      – Abel Hristodor
      Nov 22 at 17:49










    • @AbelHristodor again you name the post parameters name, email,password in the axios call, but in your server route you are using req.body.register_name to access them.
      – Gabriele Petrioli
      Nov 22 at 18:54












    • okk, but now i get ` Cannot read property 'name' of undefined```
      – Abel Hristodor
      Nov 22 at 18:59










    • @AbelHristodor you need app.use(express.json()); in your server side script.
      – Gabriele Petrioli
      Nov 22 at 19:08










    • Okk thanks :) I've been trying to solve this problem for a few days and it got very frustrating haha
      – Abel Hristodor
      Nov 22 at 19:25















    up vote
    1
    down vote













    You are using the [event.target.id] of the changed input element to update the state.



    You state expects name,email,password but receives register_name,register_email,register_password.



    You should change the id of the input elements to match those in the state or you should use the name attribute since that is what matches .



    this.setState({[event.target.name]: event.target.value});




    Keep in mind that the attribute htmlFor of the label elements also needs to match the id and not the name of the element it is linked to.





    Also, you should have noticed that something was wrong since your code will not update the input elements while you type.






    share|improve this answer





















    • oh yeah, forgot i changed them haha. Anyway, changed everything, same result
      – Abel Hristodor
      Nov 22 at 17:49










    • @AbelHristodor again you name the post parameters name, email,password in the axios call, but in your server route you are using req.body.register_name to access them.
      – Gabriele Petrioli
      Nov 22 at 18:54












    • okk, but now i get ` Cannot read property 'name' of undefined```
      – Abel Hristodor
      Nov 22 at 18:59










    • @AbelHristodor you need app.use(express.json()); in your server side script.
      – Gabriele Petrioli
      Nov 22 at 19:08










    • Okk thanks :) I've been trying to solve this problem for a few days and it got very frustrating haha
      – Abel Hristodor
      Nov 22 at 19:25













    up vote
    1
    down vote










    up vote
    1
    down vote









    You are using the [event.target.id] of the changed input element to update the state.



    You state expects name,email,password but receives register_name,register_email,register_password.



    You should change the id of the input elements to match those in the state or you should use the name attribute since that is what matches .



    this.setState({[event.target.name]: event.target.value});




    Keep in mind that the attribute htmlFor of the label elements also needs to match the id and not the name of the element it is linked to.





    Also, you should have noticed that something was wrong since your code will not update the input elements while you type.






    share|improve this answer












    You are using the [event.target.id] of the changed input element to update the state.



    You state expects name,email,password but receives register_name,register_email,register_password.



    You should change the id of the input elements to match those in the state or you should use the name attribute since that is what matches .



    this.setState({[event.target.name]: event.target.value});




    Keep in mind that the attribute htmlFor of the label elements also needs to match the id and not the name of the element it is linked to.





    Also, you should have noticed that something was wrong since your code will not update the input elements while you type.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 22 at 17:40









    Gabriele Petrioli

    148k22196252




    148k22196252












    • oh yeah, forgot i changed them haha. Anyway, changed everything, same result
      – Abel Hristodor
      Nov 22 at 17:49










    • @AbelHristodor again you name the post parameters name, email,password in the axios call, but in your server route you are using req.body.register_name to access them.
      – Gabriele Petrioli
      Nov 22 at 18:54












    • okk, but now i get ` Cannot read property 'name' of undefined```
      – Abel Hristodor
      Nov 22 at 18:59










    • @AbelHristodor you need app.use(express.json()); in your server side script.
      – Gabriele Petrioli
      Nov 22 at 19:08










    • Okk thanks :) I've been trying to solve this problem for a few days and it got very frustrating haha
      – Abel Hristodor
      Nov 22 at 19:25


















    • oh yeah, forgot i changed them haha. Anyway, changed everything, same result
      – Abel Hristodor
      Nov 22 at 17:49










    • @AbelHristodor again you name the post parameters name, email,password in the axios call, but in your server route you are using req.body.register_name to access them.
      – Gabriele Petrioli
      Nov 22 at 18:54












    • okk, but now i get ` Cannot read property 'name' of undefined```
      – Abel Hristodor
      Nov 22 at 18:59










    • @AbelHristodor you need app.use(express.json()); in your server side script.
      – Gabriele Petrioli
      Nov 22 at 19:08










    • Okk thanks :) I've been trying to solve this problem for a few days and it got very frustrating haha
      – Abel Hristodor
      Nov 22 at 19:25
















    oh yeah, forgot i changed them haha. Anyway, changed everything, same result
    – Abel Hristodor
    Nov 22 at 17:49




    oh yeah, forgot i changed them haha. Anyway, changed everything, same result
    – Abel Hristodor
    Nov 22 at 17:49












    @AbelHristodor again you name the post parameters name, email,password in the axios call, but in your server route you are using req.body.register_name to access them.
    – Gabriele Petrioli
    Nov 22 at 18:54






    @AbelHristodor again you name the post parameters name, email,password in the axios call, but in your server route you are using req.body.register_name to access them.
    – Gabriele Petrioli
    Nov 22 at 18:54














    okk, but now i get ` Cannot read property 'name' of undefined```
    – Abel Hristodor
    Nov 22 at 18:59




    okk, but now i get ` Cannot read property 'name' of undefined```
    – Abel Hristodor
    Nov 22 at 18:59












    @AbelHristodor you need app.use(express.json()); in your server side script.
    – Gabriele Petrioli
    Nov 22 at 19:08




    @AbelHristodor you need app.use(express.json()); in your server side script.
    – Gabriele Petrioli
    Nov 22 at 19:08












    Okk thanks :) I've been trying to solve this problem for a few days and it got very frustrating haha
    – Abel Hristodor
    Nov 22 at 19:25




    Okk thanks :) I've been trying to solve this problem for a few days and it got very frustrating haha
    – Abel Hristodor
    Nov 22 at 19:25










    up vote
    0
    down vote













    Everything works out of the box with just bare fetch.
    Here is gist, just make sure you attached bodyParser to express instance



    const bodyParser = require('body-parser');
    ...
    app.use(bodyParser.json());


    axios lib is useful if you want to upload physical files with FormData






    share|improve this answer

























      up vote
      0
      down vote













      Everything works out of the box with just bare fetch.
      Here is gist, just make sure you attached bodyParser to express instance



      const bodyParser = require('body-parser');
      ...
      app.use(bodyParser.json());


      axios lib is useful if you want to upload physical files with FormData






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        Everything works out of the box with just bare fetch.
        Here is gist, just make sure you attached bodyParser to express instance



        const bodyParser = require('body-parser');
        ...
        app.use(bodyParser.json());


        axios lib is useful if you want to upload physical files with FormData






        share|improve this answer












        Everything works out of the box with just bare fetch.
        Here is gist, just make sure you attached bodyParser to express instance



        const bodyParser = require('body-parser');
        ...
        app.use(bodyParser.json());


        axios lib is useful if you want to upload physical files with FormData







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 at 20:05









        bFunc

        644712




        644712






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53435712%2fcant-post-data-to-express-using-react%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            What visual should I use to simply compare current year value vs last year in Power BI desktop

            Alexandru Averescu

            Trompette piccolo