我已快速配置为路由到redirect
,如下所示:
在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;
app.js中的:
...
var redirect = require('./routes/redirect');
var app = express();
...
app.use('/redirect', redirect);
并在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;
我在代码的TODO部分中包含了我的问题描述。有没有办法完全使用Node + React而不安装所有类型的插件?
答案 0 :(得分:5)
您可以使用大多数现代浏览器支持的fetch
API。见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;
希望它有所帮助。