Reputation: 293
I have express configured to route to redirect
as follow:
in routes/redirect.js:
var express = require('express');
var router = express.Router();
router.post('/', function(req, res, next) {
res.send('received POST data: ' + req.body.data);
});
module.exports = router;
in app.js:
...
var redirect = require('./routes/redirect');
var app = express();
...
app.use('/redirect', redirect);
and in component.jsx:
var React = require('react');
var Component = React.createClass({
render: function(){
return (
<form>
<input type="text" ref="data" placeholder="Send some data"/>
<button onClick={this.handleSubmit}>Send</button>
</form>
);
},
handleSubmit: function() {
var data = this.refs.data.getDOMNode().value;
// TODO: how do I send 'data' as POST request and redirect to /redirect ?
// i.e. POST and redirect to localhost:3000/redirect like in a classic
// form submit{action='redirect',method='post'} way
}
});
module.exports=Component;
I've included the description of my question in the TODO section of the code. Is there a way to do it purely with Node+React without installing all kind of plugins?
Upvotes: 5
Views: 17089
Reputation: 545
You could use the fetch
API which is supported in most modern browsers. See MDN for reference
var Component = React.createClass({
render: function(){
return (
<form>
<input type="text" ref="data" placeholder="Send some data"/>
<button onClick={this.handleSubmit}>Send</button>
</form>
);
},
handleSubmit: function(e) {
e.preventDefault();
var data = this.refs.data.getDOMNode().value;
fetch("<url to where to post>", {
method: "POST",
body: 'data'
}).then(this.handleRedirect)
},
handleRedirect: function(res){
if( res.status === 200 ){
// redirect here
// window.location.href = 'http://localhost:300/redirect';
}else {
// Something went wrong here
}
}
});
module.exports=Component;
Hope it helps.
Upvotes: 7