GitHub Fetch填充不与React表单组件形成顶点

我正在使用GitHub和React 获取 api的polyfill。 提交表单的例子如下:

var form = document.querySelector('form') fetch('/users', { method: 'post', body: new FormData(form) }) 

我的代码目前看起来像这样的组件内部

 handleSubmit (event) { event.preventDefault(); fetch('/api/user/', { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, method: 'post', body: JSON.stringify(this.state) }).then(function(response) { console.log(response); }) }, 

在应用程序状态中,我持有正在发送的数据。 这是一个简单的对象。

 { email: 'someemail@email.com', password: 'password', name: 'Some Name' } 

我试图从事件event.target传递表单本身,以及通过ID属性获取表单,并将其传递给正文。

在服务器上,我使用NodeJs来捕获请求中的表单主体。 但是,如果我没有通过头'Content-Type': 'application/x-www-form-urlencoded' ,请求是空'Content-Type': 'application/x-www-form-urlencoded' 。 但是当我传递它的整个身体是一个空的键值,但只有当我使用JSON.stringify(this.state) 。 如下:

'{email: 'someemail@email.com',password: 'password',name: 'Some Name'}': ''

我也尝试传递没有标题,以及下面的标题。

 headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', } 

我通过webpack添加fetch模块作为插件。

 new webpack.ProvidePlugin({ 'Promise': 'exports?global.Promise!es6-promise', 'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch' }) 

我卡住了,任何帮助表示赞赏。

目前,我有一个非常丑陋的黑客攻击服务器上将key=>value对再次转换成一个对象,但这是一个可耻的事件来分享它。

 var userInfo = req.body; var tempVals; //hack to fixed fetch if(!userInfo.email) { for(values in req.body) { tempVals = JSON.parse(values); if(tempVals.email) { userInfo = tempVals; break; } } } 

我说这是丑陋的

UPDATE

感谢米歇尔,我能够弄清楚,这是parsing表单数据。 我使用了body-parser模块。 我无法使用当前设置读取数据。 我不得不在客户端更改我的代码,如下所示:

 handleSubmit (e) { e.preventDefault(); fetch('/api/user/', { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: 'post', body: JSON.stringify(this.state) }).then(function(response) { console.log(response); }) } 

并在后端,我不得不添加到我的路线的JSON身体分析器如下

 var bodyParser = require('body-parser'); var jsonParser = bodyParser.json(); app.post('/user', jsonParser, function(req, res) { //do something with the data }); 

你发布的例子:

 var form = document.querySelector('form') fetch('/users', { method: 'post', body: new FormData(form) }) 

是张贴表单数据的示例(有关更多信息,请参阅此堆栈溢出问题 )。 您正在尝试提交JSON数据,README中的下一个示例是您应该使用的方法:

 fetch('/users', { method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Hubot', login: 'hubot', }) }) 

所以你的代码看起来像

 handleSubmit (event) { event.preventDefault(); fetch('/api/user/', { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: 'post', body: JSON.stringify(this.state) }).then(function(response) { console.log(response); }) }, 

您还需要在Express应用程序中安装适当的中间件来parsingJSON主体(例如body-parser ):

 var bodyParser = require('body-parser'); // ... app.use(bodyParser.json()); app.post('/user', function(req, res) { //do something with the data });