我正在使用GitHub的带有React的fetch 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属性获取表单并将其传递到主体。
在服务器上,我使用NodeJ来捕获请求中的表单主体。但是如果我不传递头'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
});
您发布的示例:
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应用程序中安装适当的中间件来解析JSON主体(例如,主体解析器):
var bodyParser = require('body-parser');
// ...
app.use(bodyParser.json());
app.post('/user', function(req, res) {
//do something with the data
});