【问题标题】:GitHub Fetch polyfill does not summit form body with React form componetGitHub Fetch polyfill 不使用 React 表单组件提交表单主体
【发布时间】: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


    【解决方案1】:

    您发布的示例:

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

    是发布表单数据的示例(请参阅this Stack Overflow question 了解更多信息)。您正在尝试提交 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 正文(例如,body-parser):

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

    【讨论】:

    • 嗨,米歇尔,感谢您的回答。我实际上已经尝试过,两者都有。我尝试从event.target 提交表单,但后端得到一个空对象{}。我也尝试将其作为示例。我绝望地尝试了文档中的所有方法,包括以 JSON 格式发送数据
    • @JoseCarrillo 您的 Express 中间件中是否安装了正文解析模块?即使解析表单编码体,您仍然需要它。
    • 嗨 Michelle,是的,我正在使用 body-parser 模块。 var bodyParser = require('body-parser')。这是我的 Node 应用程序中的设置 var urlencodedParser = bodyParser.urlencoded({ extended: false })
    • @JoseCarrillo 在这种情况下,我希望使用'Content-Type': 'application/x-www-form-urlencoded'body: new FormData(evt.target)(假设evt.target 是表单)来工作。 =\
    • 感谢您的帮助,它确实与身体解析器中间件有关。我不确定为什么。我包含了body-parse 的json 解析器,并将数据作为JSON 发送,并带有完成这项工作的application/json 标头。感谢您为我指明正确的方向。我更新了我的代码。如果您想更新您的答案,我可以将其标记为答案。
    猜你喜欢
    • 2021-07-06
    • 2016-11-14
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多