make http post request with reactJs and NodeJs












2















I have a registration form in one of my reactJs files, which takes all values of input fields (works as I expect).
SignUp.js






import React, { Component } from 'react';
import { Link } from 'react-router-dom';

class SignUpForm extends Component {
constructor() {
super();

this.state = {
email: '',
password: '',
username: '',
hasAgreed: false,
formErrors: {email: '', password: ''},
emailValid: false,
passwordValid: false,
formValid: false
};

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

handleChange(e) {
let target = e.target;
let value = target.type === 'checkbox' ? target.checked : target.value;
let name = target.name;

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

handleSubmit(e) {
e.preventDefault();

console.log('The form was submitted with the following data:');

console.log([this.state.email, cryptr.encrypt(this.state.password), this.state.username, this.state.hasAgreed]);

//I want to send my above data to node server

}

render() {
return (
<div className="FormCenter">
<form onSubmit={this.handleSubmit} className="FormFields" method="POST" action="/register">
<div className="FormField">
<label htmlFor="name">Username</label>
<input type="text" id="name" placeholder="Enter your username" name="username" value={this.state.username} onChange={this.handleChange} />
</div>
<div className="FormField">
<label htmlFor="password">Password</label>
<input type="password" id="password" placeholder="Enter your password" name="password" value={this.state.password} onChange={this.handleChange} />
<div className="FormField">
<label htmlFor="email">E-Mail Address</label>
<input type="email" id="email" placeholder="Enter your email" name="email" value={this.state.email} onChange={this.handleChange} />
</div>
</div>

<div className="FormField">
<label>
<input type="checkbox" name="hasAgreed" value={this.state.hasAgreed} onChange={this.handleChange} /> I agree all statements in <a href="google.com">terms of service</a>
</label>
</div>
</form>
</div>
);
}
}

export default SignUpForm;





Now I want to send the mentioned data to the created node server.
server.js






const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "src/containers/user")));

//the request in which I expect input data
app.post('/register', (req, res) => {
if (!req.body) return res.sendStatus(400);
console.log(req.body, "body");
res.send('welcome, ' + req.body.username)
});

app.listen(5000, () => {
console.log("is listening on port 5000");
});





As I expect, in form tag writing method="POST" action="/register"would do it's job, but even the console.log from /register request is not responding.


Note: The next thing I should implement is to write all the data in txt file. So fetching the data in back end is a must.










share|improve this question























  • Use apisauce or axios, otherwise you have to do an old fashioned XMLHttpRequest call

    – AnonymousSB
    Nov 20 '18 at 0:21











  • writing this inside handleSubmit didn't help axios.post('/register') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });

    – reactive
    Nov 20 '18 at 0:23








  • 1





    You’re not sending anything with your post. The second argument is supposed to be your data

    – AnonymousSB
    Nov 20 '18 at 0:24
















2















I have a registration form in one of my reactJs files, which takes all values of input fields (works as I expect).
SignUp.js






import React, { Component } from 'react';
import { Link } from 'react-router-dom';

class SignUpForm extends Component {
constructor() {
super();

this.state = {
email: '',
password: '',
username: '',
hasAgreed: false,
formErrors: {email: '', password: ''},
emailValid: false,
passwordValid: false,
formValid: false
};

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

handleChange(e) {
let target = e.target;
let value = target.type === 'checkbox' ? target.checked : target.value;
let name = target.name;

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

handleSubmit(e) {
e.preventDefault();

console.log('The form was submitted with the following data:');

console.log([this.state.email, cryptr.encrypt(this.state.password), this.state.username, this.state.hasAgreed]);

//I want to send my above data to node server

}

render() {
return (
<div className="FormCenter">
<form onSubmit={this.handleSubmit} className="FormFields" method="POST" action="/register">
<div className="FormField">
<label htmlFor="name">Username</label>
<input type="text" id="name" placeholder="Enter your username" name="username" value={this.state.username} onChange={this.handleChange} />
</div>
<div className="FormField">
<label htmlFor="password">Password</label>
<input type="password" id="password" placeholder="Enter your password" name="password" value={this.state.password} onChange={this.handleChange} />
<div className="FormField">
<label htmlFor="email">E-Mail Address</label>
<input type="email" id="email" placeholder="Enter your email" name="email" value={this.state.email} onChange={this.handleChange} />
</div>
</div>

<div className="FormField">
<label>
<input type="checkbox" name="hasAgreed" value={this.state.hasAgreed} onChange={this.handleChange} /> I agree all statements in <a href="google.com">terms of service</a>
</label>
</div>
</form>
</div>
);
}
}

export default SignUpForm;





Now I want to send the mentioned data to the created node server.
server.js






const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "src/containers/user")));

//the request in which I expect input data
app.post('/register', (req, res) => {
if (!req.body) return res.sendStatus(400);
console.log(req.body, "body");
res.send('welcome, ' + req.body.username)
});

app.listen(5000, () => {
console.log("is listening on port 5000");
});





As I expect, in form tag writing method="POST" action="/register"would do it's job, but even the console.log from /register request is not responding.


Note: The next thing I should implement is to write all the data in txt file. So fetching the data in back end is a must.










share|improve this question























  • Use apisauce or axios, otherwise you have to do an old fashioned XMLHttpRequest call

    – AnonymousSB
    Nov 20 '18 at 0:21











  • writing this inside handleSubmit didn't help axios.post('/register') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });

    – reactive
    Nov 20 '18 at 0:23








  • 1





    You’re not sending anything with your post. The second argument is supposed to be your data

    – AnonymousSB
    Nov 20 '18 at 0:24














2












2








2


1






I have a registration form in one of my reactJs files, which takes all values of input fields (works as I expect).
SignUp.js






import React, { Component } from 'react';
import { Link } from 'react-router-dom';

class SignUpForm extends Component {
constructor() {
super();

this.state = {
email: '',
password: '',
username: '',
hasAgreed: false,
formErrors: {email: '', password: ''},
emailValid: false,
passwordValid: false,
formValid: false
};

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

handleChange(e) {
let target = e.target;
let value = target.type === 'checkbox' ? target.checked : target.value;
let name = target.name;

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

handleSubmit(e) {
e.preventDefault();

console.log('The form was submitted with the following data:');

console.log([this.state.email, cryptr.encrypt(this.state.password), this.state.username, this.state.hasAgreed]);

//I want to send my above data to node server

}

render() {
return (
<div className="FormCenter">
<form onSubmit={this.handleSubmit} className="FormFields" method="POST" action="/register">
<div className="FormField">
<label htmlFor="name">Username</label>
<input type="text" id="name" placeholder="Enter your username" name="username" value={this.state.username} onChange={this.handleChange} />
</div>
<div className="FormField">
<label htmlFor="password">Password</label>
<input type="password" id="password" placeholder="Enter your password" name="password" value={this.state.password} onChange={this.handleChange} />
<div className="FormField">
<label htmlFor="email">E-Mail Address</label>
<input type="email" id="email" placeholder="Enter your email" name="email" value={this.state.email} onChange={this.handleChange} />
</div>
</div>

<div className="FormField">
<label>
<input type="checkbox" name="hasAgreed" value={this.state.hasAgreed} onChange={this.handleChange} /> I agree all statements in <a href="google.com">terms of service</a>
</label>
</div>
</form>
</div>
);
}
}

export default SignUpForm;





Now I want to send the mentioned data to the created node server.
server.js






const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "src/containers/user")));

//the request in which I expect input data
app.post('/register', (req, res) => {
if (!req.body) return res.sendStatus(400);
console.log(req.body, "body");
res.send('welcome, ' + req.body.username)
});

app.listen(5000, () => {
console.log("is listening on port 5000");
});





As I expect, in form tag writing method="POST" action="/register"would do it's job, but even the console.log from /register request is not responding.


Note: The next thing I should implement is to write all the data in txt file. So fetching the data in back end is a must.










share|improve this question














I have a registration form in one of my reactJs files, which takes all values of input fields (works as I expect).
SignUp.js






import React, { Component } from 'react';
import { Link } from 'react-router-dom';

class SignUpForm extends Component {
constructor() {
super();

this.state = {
email: '',
password: '',
username: '',
hasAgreed: false,
formErrors: {email: '', password: ''},
emailValid: false,
passwordValid: false,
formValid: false
};

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

handleChange(e) {
let target = e.target;
let value = target.type === 'checkbox' ? target.checked : target.value;
let name = target.name;

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

handleSubmit(e) {
e.preventDefault();

console.log('The form was submitted with the following data:');

console.log([this.state.email, cryptr.encrypt(this.state.password), this.state.username, this.state.hasAgreed]);

//I want to send my above data to node server

}

render() {
return (
<div className="FormCenter">
<form onSubmit={this.handleSubmit} className="FormFields" method="POST" action="/register">
<div className="FormField">
<label htmlFor="name">Username</label>
<input type="text" id="name" placeholder="Enter your username" name="username" value={this.state.username} onChange={this.handleChange} />
</div>
<div className="FormField">
<label htmlFor="password">Password</label>
<input type="password" id="password" placeholder="Enter your password" name="password" value={this.state.password} onChange={this.handleChange} />
<div className="FormField">
<label htmlFor="email">E-Mail Address</label>
<input type="email" id="email" placeholder="Enter your email" name="email" value={this.state.email} onChange={this.handleChange} />
</div>
</div>

<div className="FormField">
<label>
<input type="checkbox" name="hasAgreed" value={this.state.hasAgreed} onChange={this.handleChange} /> I agree all statements in <a href="google.com">terms of service</a>
</label>
</div>
</form>
</div>
);
}
}

export default SignUpForm;





Now I want to send the mentioned data to the created node server.
server.js






const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "src/containers/user")));

//the request in which I expect input data
app.post('/register', (req, res) => {
if (!req.body) return res.sendStatus(400);
console.log(req.body, "body");
res.send('welcome, ' + req.body.username)
});

app.listen(5000, () => {
console.log("is listening on port 5000");
});





As I expect, in form tag writing method="POST" action="/register"would do it's job, but even the console.log from /register request is not responding.


Note: The next thing I should implement is to write all the data in txt file. So fetching the data in back end is a must.






import React, { Component } from 'react';
import { Link } from 'react-router-dom';

class SignUpForm extends Component {
constructor() {
super();

this.state = {
email: '',
password: '',
username: '',
hasAgreed: false,
formErrors: {email: '', password: ''},
emailValid: false,
passwordValid: false,
formValid: false
};

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

handleChange(e) {
let target = e.target;
let value = target.type === 'checkbox' ? target.checked : target.value;
let name = target.name;

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

handleSubmit(e) {
e.preventDefault();

console.log('The form was submitted with the following data:');

console.log([this.state.email, cryptr.encrypt(this.state.password), this.state.username, this.state.hasAgreed]);

//I want to send my above data to node server

}

render() {
return (
<div className="FormCenter">
<form onSubmit={this.handleSubmit} className="FormFields" method="POST" action="/register">
<div className="FormField">
<label htmlFor="name">Username</label>
<input type="text" id="name" placeholder="Enter your username" name="username" value={this.state.username} onChange={this.handleChange} />
</div>
<div className="FormField">
<label htmlFor="password">Password</label>
<input type="password" id="password" placeholder="Enter your password" name="password" value={this.state.password} onChange={this.handleChange} />
<div className="FormField">
<label htmlFor="email">E-Mail Address</label>
<input type="email" id="email" placeholder="Enter your email" name="email" value={this.state.email} onChange={this.handleChange} />
</div>
</div>

<div className="FormField">
<label>
<input type="checkbox" name="hasAgreed" value={this.state.hasAgreed} onChange={this.handleChange} /> I agree all statements in <a href="google.com">terms of service</a>
</label>
</div>
</form>
</div>
);
}
}

export default SignUpForm;





import React, { Component } from 'react';
import { Link } from 'react-router-dom';

class SignUpForm extends Component {
constructor() {
super();

this.state = {
email: '',
password: '',
username: '',
hasAgreed: false,
formErrors: {email: '', password: ''},
emailValid: false,
passwordValid: false,
formValid: false
};

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

handleChange(e) {
let target = e.target;
let value = target.type === 'checkbox' ? target.checked : target.value;
let name = target.name;

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

handleSubmit(e) {
e.preventDefault();

console.log('The form was submitted with the following data:');

console.log([this.state.email, cryptr.encrypt(this.state.password), this.state.username, this.state.hasAgreed]);

//I want to send my above data to node server

}

render() {
return (
<div className="FormCenter">
<form onSubmit={this.handleSubmit} className="FormFields" method="POST" action="/register">
<div className="FormField">
<label htmlFor="name">Username</label>
<input type="text" id="name" placeholder="Enter your username" name="username" value={this.state.username} onChange={this.handleChange} />
</div>
<div className="FormField">
<label htmlFor="password">Password</label>
<input type="password" id="password" placeholder="Enter your password" name="password" value={this.state.password} onChange={this.handleChange} />
<div className="FormField">
<label htmlFor="email">E-Mail Address</label>
<input type="email" id="email" placeholder="Enter your email" name="email" value={this.state.email} onChange={this.handleChange} />
</div>
</div>

<div className="FormField">
<label>
<input type="checkbox" name="hasAgreed" value={this.state.hasAgreed} onChange={this.handleChange} /> I agree all statements in <a href="google.com">terms of service</a>
</label>
</div>
</form>
</div>
);
}
}

export default SignUpForm;





const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "src/containers/user")));

//the request in which I expect input data
app.post('/register', (req, res) => {
if (!req.body) return res.sendStatus(400);
console.log(req.body, "body");
res.send('welcome, ' + req.body.username)
});

app.listen(5000, () => {
console.log("is listening on port 5000");
});





const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "src/containers/user")));

//the request in which I expect input data
app.post('/register', (req, res) => {
if (!req.body) return res.sendStatus(400);
console.log(req.body, "body");
res.send('welcome, ' + req.body.username)
});

app.listen(5000, () => {
console.log("is listening on port 5000");
});






javascript node.js reactjs http






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 '18 at 0:18









reactivereactive

34




34













  • Use apisauce or axios, otherwise you have to do an old fashioned XMLHttpRequest call

    – AnonymousSB
    Nov 20 '18 at 0:21











  • writing this inside handleSubmit didn't help axios.post('/register') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });

    – reactive
    Nov 20 '18 at 0:23








  • 1





    You’re not sending anything with your post. The second argument is supposed to be your data

    – AnonymousSB
    Nov 20 '18 at 0:24



















  • Use apisauce or axios, otherwise you have to do an old fashioned XMLHttpRequest call

    – AnonymousSB
    Nov 20 '18 at 0:21











  • writing this inside handleSubmit didn't help axios.post('/register') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });

    – reactive
    Nov 20 '18 at 0:23








  • 1





    You’re not sending anything with your post. The second argument is supposed to be your data

    – AnonymousSB
    Nov 20 '18 at 0:24

















Use apisauce or axios, otherwise you have to do an old fashioned XMLHttpRequest call

– AnonymousSB
Nov 20 '18 at 0:21





Use apisauce or axios, otherwise you have to do an old fashioned XMLHttpRequest call

– AnonymousSB
Nov 20 '18 at 0:21













writing this inside handleSubmit didn't help axios.post('/register') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });

– reactive
Nov 20 '18 at 0:23







writing this inside handleSubmit didn't help axios.post('/register') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });

– reactive
Nov 20 '18 at 0:23






1




1





You’re not sending anything with your post. The second argument is supposed to be your data

– AnonymousSB
Nov 20 '18 at 0:24





You’re not sending anything with your post. The second argument is supposed to be your data

– AnonymousSB
Nov 20 '18 at 0:24












2 Answers
2






active

oldest

votes


















0














The default behavior of a form is to submit when a submit button is clicked, or if a user hits enter. In your case however, you have a submit handler like so;



handleSubmit(e) {
e.preventDefault();

console.log('The form was submitted with the following data:');

console.log([this.state.email, cryptr.encrypt(this.state.password), this.state.username, this.state.hasAgreed]);

//I want to send my above data to node server

}


In this handler your are writing e.preventDefault(); which as the name implies, prevents the form's default behavior from happening. As a result no request is actually being made to the server.



Now the surest way I know to make this work, would be to use some kind of ajax library. You can use fetch, or something like axios.



The other way which MAY work is to remove the e.preventDefault();. Now this way is a bit more tricky. Usually react apps are not served from the same server as the api, in which case your request's url would need to look something more like this.
http://localhost:5000/register. Alternatively, you can tell webpack dev server to proxy your requests. Even then I personally am not sure this would work simply because I have never tried it.



Its important to note, either approach you choose will require the full url in the request if the react app is not served from the same place as the api, or if there is no proxying done by wepback. In other words, you may very well need http://localhost:5000/register.



My suggestion would be to use an ajax library like I mentioned.



Hope this helps.






share|improve this answer
























  • The problem is I wasn't using proxy. But as no other answer was appeared, I leave it as an acceptable one. Didn't know preventDefault() would cause any error.

    – reactive
    Dec 3 '18 at 17:44



















1














What you need to do is pass the data as an object to axios like so, which you indicated you have installed in your project.



const formData = {
email: this.state.email,
password: cryptr.encrypt(this.state.password)
username: this.state.username,
hasAgreed: this.state.hasAgreed
}

axios({
method: 'post',
url: '/register',
data: formData,
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
.then(function (response) {
//handle success
})
.catch(function (response) {
//handle error
});





share|improve this answer


























  • Error: Request failed with status code 404. This is what I get.

    – reactive
    Nov 20 '18 at 0:31











  • Is “/register” on the same server as your React app? You may need to put a full http path

    – AnonymousSB
    Nov 20 '18 at 0:33













  • No I use two separate servers, one is for reactJs another one is node server. where should I put the full path?

    – reactive
    Nov 20 '18 at 0:39











  • Where it says “url”, change “/register” to the full path

    – AnonymousSB
    Nov 20 '18 at 0:41













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',
autoActivateHeartbeat: false,
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%2f53384475%2fmake-http-post-request-with-reactjs-and-nodejs%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














The default behavior of a form is to submit when a submit button is clicked, or if a user hits enter. In your case however, you have a submit handler like so;



handleSubmit(e) {
e.preventDefault();

console.log('The form was submitted with the following data:');

console.log([this.state.email, cryptr.encrypt(this.state.password), this.state.username, this.state.hasAgreed]);

//I want to send my above data to node server

}


In this handler your are writing e.preventDefault(); which as the name implies, prevents the form's default behavior from happening. As a result no request is actually being made to the server.



Now the surest way I know to make this work, would be to use some kind of ajax library. You can use fetch, or something like axios.



The other way which MAY work is to remove the e.preventDefault();. Now this way is a bit more tricky. Usually react apps are not served from the same server as the api, in which case your request's url would need to look something more like this.
http://localhost:5000/register. Alternatively, you can tell webpack dev server to proxy your requests. Even then I personally am not sure this would work simply because I have never tried it.



Its important to note, either approach you choose will require the full url in the request if the react app is not served from the same place as the api, or if there is no proxying done by wepback. In other words, you may very well need http://localhost:5000/register.



My suggestion would be to use an ajax library like I mentioned.



Hope this helps.






share|improve this answer
























  • The problem is I wasn't using proxy. But as no other answer was appeared, I leave it as an acceptable one. Didn't know preventDefault() would cause any error.

    – reactive
    Dec 3 '18 at 17:44
















0














The default behavior of a form is to submit when a submit button is clicked, or if a user hits enter. In your case however, you have a submit handler like so;



handleSubmit(e) {
e.preventDefault();

console.log('The form was submitted with the following data:');

console.log([this.state.email, cryptr.encrypt(this.state.password), this.state.username, this.state.hasAgreed]);

//I want to send my above data to node server

}


In this handler your are writing e.preventDefault(); which as the name implies, prevents the form's default behavior from happening. As a result no request is actually being made to the server.



Now the surest way I know to make this work, would be to use some kind of ajax library. You can use fetch, or something like axios.



The other way which MAY work is to remove the e.preventDefault();. Now this way is a bit more tricky. Usually react apps are not served from the same server as the api, in which case your request's url would need to look something more like this.
http://localhost:5000/register. Alternatively, you can tell webpack dev server to proxy your requests. Even then I personally am not sure this would work simply because I have never tried it.



Its important to note, either approach you choose will require the full url in the request if the react app is not served from the same place as the api, or if there is no proxying done by wepback. In other words, you may very well need http://localhost:5000/register.



My suggestion would be to use an ajax library like I mentioned.



Hope this helps.






share|improve this answer
























  • The problem is I wasn't using proxy. But as no other answer was appeared, I leave it as an acceptable one. Didn't know preventDefault() would cause any error.

    – reactive
    Dec 3 '18 at 17:44














0












0








0







The default behavior of a form is to submit when a submit button is clicked, or if a user hits enter. In your case however, you have a submit handler like so;



handleSubmit(e) {
e.preventDefault();

console.log('The form was submitted with the following data:');

console.log([this.state.email, cryptr.encrypt(this.state.password), this.state.username, this.state.hasAgreed]);

//I want to send my above data to node server

}


In this handler your are writing e.preventDefault(); which as the name implies, prevents the form's default behavior from happening. As a result no request is actually being made to the server.



Now the surest way I know to make this work, would be to use some kind of ajax library. You can use fetch, or something like axios.



The other way which MAY work is to remove the e.preventDefault();. Now this way is a bit more tricky. Usually react apps are not served from the same server as the api, in which case your request's url would need to look something more like this.
http://localhost:5000/register. Alternatively, you can tell webpack dev server to proxy your requests. Even then I personally am not sure this would work simply because I have never tried it.



Its important to note, either approach you choose will require the full url in the request if the react app is not served from the same place as the api, or if there is no proxying done by wepback. In other words, you may very well need http://localhost:5000/register.



My suggestion would be to use an ajax library like I mentioned.



Hope this helps.






share|improve this answer













The default behavior of a form is to submit when a submit button is clicked, or if a user hits enter. In your case however, you have a submit handler like so;



handleSubmit(e) {
e.preventDefault();

console.log('The form was submitted with the following data:');

console.log([this.state.email, cryptr.encrypt(this.state.password), this.state.username, this.state.hasAgreed]);

//I want to send my above data to node server

}


In this handler your are writing e.preventDefault(); which as the name implies, prevents the form's default behavior from happening. As a result no request is actually being made to the server.



Now the surest way I know to make this work, would be to use some kind of ajax library. You can use fetch, or something like axios.



The other way which MAY work is to remove the e.preventDefault();. Now this way is a bit more tricky. Usually react apps are not served from the same server as the api, in which case your request's url would need to look something more like this.
http://localhost:5000/register. Alternatively, you can tell webpack dev server to proxy your requests. Even then I personally am not sure this would work simply because I have never tried it.



Its important to note, either approach you choose will require the full url in the request if the react app is not served from the same place as the api, or if there is no proxying done by wepback. In other words, you may very well need http://localhost:5000/register.



My suggestion would be to use an ajax library like I mentioned.



Hope this helps.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 20 '18 at 0:31









Chaim FriedmanChaim Friedman

2,758832




2,758832













  • The problem is I wasn't using proxy. But as no other answer was appeared, I leave it as an acceptable one. Didn't know preventDefault() would cause any error.

    – reactive
    Dec 3 '18 at 17:44



















  • The problem is I wasn't using proxy. But as no other answer was appeared, I leave it as an acceptable one. Didn't know preventDefault() would cause any error.

    – reactive
    Dec 3 '18 at 17:44

















The problem is I wasn't using proxy. But as no other answer was appeared, I leave it as an acceptable one. Didn't know preventDefault() would cause any error.

– reactive
Dec 3 '18 at 17:44





The problem is I wasn't using proxy. But as no other answer was appeared, I leave it as an acceptable one. Didn't know preventDefault() would cause any error.

– reactive
Dec 3 '18 at 17:44













1














What you need to do is pass the data as an object to axios like so, which you indicated you have installed in your project.



const formData = {
email: this.state.email,
password: cryptr.encrypt(this.state.password)
username: this.state.username,
hasAgreed: this.state.hasAgreed
}

axios({
method: 'post',
url: '/register',
data: formData,
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
.then(function (response) {
//handle success
})
.catch(function (response) {
//handle error
});





share|improve this answer


























  • Error: Request failed with status code 404. This is what I get.

    – reactive
    Nov 20 '18 at 0:31











  • Is “/register” on the same server as your React app? You may need to put a full http path

    – AnonymousSB
    Nov 20 '18 at 0:33













  • No I use two separate servers, one is for reactJs another one is node server. where should I put the full path?

    – reactive
    Nov 20 '18 at 0:39











  • Where it says “url”, change “/register” to the full path

    – AnonymousSB
    Nov 20 '18 at 0:41


















1














What you need to do is pass the data as an object to axios like so, which you indicated you have installed in your project.



const formData = {
email: this.state.email,
password: cryptr.encrypt(this.state.password)
username: this.state.username,
hasAgreed: this.state.hasAgreed
}

axios({
method: 'post',
url: '/register',
data: formData,
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
.then(function (response) {
//handle success
})
.catch(function (response) {
//handle error
});





share|improve this answer


























  • Error: Request failed with status code 404. This is what I get.

    – reactive
    Nov 20 '18 at 0:31











  • Is “/register” on the same server as your React app? You may need to put a full http path

    – AnonymousSB
    Nov 20 '18 at 0:33













  • No I use two separate servers, one is for reactJs another one is node server. where should I put the full path?

    – reactive
    Nov 20 '18 at 0:39











  • Where it says “url”, change “/register” to the full path

    – AnonymousSB
    Nov 20 '18 at 0:41
















1












1








1







What you need to do is pass the data as an object to axios like so, which you indicated you have installed in your project.



const formData = {
email: this.state.email,
password: cryptr.encrypt(this.state.password)
username: this.state.username,
hasAgreed: this.state.hasAgreed
}

axios({
method: 'post',
url: '/register',
data: formData,
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
.then(function (response) {
//handle success
})
.catch(function (response) {
//handle error
});





share|improve this answer















What you need to do is pass the data as an object to axios like so, which you indicated you have installed in your project.



const formData = {
email: this.state.email,
password: cryptr.encrypt(this.state.password)
username: this.state.username,
hasAgreed: this.state.hasAgreed
}

axios({
method: 'post',
url: '/register',
data: formData,
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
.then(function (response) {
//handle success
})
.catch(function (response) {
//handle error
});






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 20 '18 at 1:39

























answered Nov 20 '18 at 0:27









AnonymousSBAnonymousSB

2,194221




2,194221













  • Error: Request failed with status code 404. This is what I get.

    – reactive
    Nov 20 '18 at 0:31











  • Is “/register” on the same server as your React app? You may need to put a full http path

    – AnonymousSB
    Nov 20 '18 at 0:33













  • No I use two separate servers, one is for reactJs another one is node server. where should I put the full path?

    – reactive
    Nov 20 '18 at 0:39











  • Where it says “url”, change “/register” to the full path

    – AnonymousSB
    Nov 20 '18 at 0:41





















  • Error: Request failed with status code 404. This is what I get.

    – reactive
    Nov 20 '18 at 0:31











  • Is “/register” on the same server as your React app? You may need to put a full http path

    – AnonymousSB
    Nov 20 '18 at 0:33













  • No I use two separate servers, one is for reactJs another one is node server. where should I put the full path?

    – reactive
    Nov 20 '18 at 0:39











  • Where it says “url”, change “/register” to the full path

    – AnonymousSB
    Nov 20 '18 at 0:41



















Error: Request failed with status code 404. This is what I get.

– reactive
Nov 20 '18 at 0:31





Error: Request failed with status code 404. This is what I get.

– reactive
Nov 20 '18 at 0:31













Is “/register” on the same server as your React app? You may need to put a full http path

– AnonymousSB
Nov 20 '18 at 0:33







Is “/register” on the same server as your React app? You may need to put a full http path

– AnonymousSB
Nov 20 '18 at 0:33















No I use two separate servers, one is for reactJs another one is node server. where should I put the full path?

– reactive
Nov 20 '18 at 0:39





No I use two separate servers, one is for reactJs another one is node server. where should I put the full path?

– reactive
Nov 20 '18 at 0:39













Where it says “url”, change “/register” to the full path

– AnonymousSB
Nov 20 '18 at 0:41







Where it says “url”, change “/register” to the full path

– AnonymousSB
Nov 20 '18 at 0:41




















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.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384475%2fmake-http-post-request-with-reactjs-and-nodejs%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

How to change which sound is reproduced for terminal bell?

Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

Can I use Tabulator js library in my java Spring + Thymeleaf project?