【发布时间】:2016-04-10 03:53:19
【问题描述】:
我正在使用 GitHub 的 fetch api polyfill 和 React。提交表单的示例如下:
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',则请求为空。但是当我确实传递它时,整个主体都是带有空键的值,但只有当我使用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;
}
}
}
...我说它很丑。
更新
感谢 Michelle,我能够弄清楚这与解析表单数据有关。我使用了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
});
【问题讨论】:
标签: javascript node.js reactjs