【问题标题】:How to properly send JSON data using SuperAgent on React如何在 React 上使用 SuperAgent 正确发送 JSON 数据
【发布时间】:2017-12-04 18:45:17
【问题描述】:

我正在将我的 react 应用程序的状态发送到服务器(与前端服务器不同)。

        request.post('http://localhost:8000/guide')
        .send(JSON.stringify(this.state))
        .end((err, resp) => {
            if (err) console.log('Error: ' + err);
            else {
                console.log(resp.text);
            }
        });

问题出在接收端(后端服务器),我在 req.body 上得到以下信息:

{ '{"mainColor":"#F44336","accentColor":"#FFC107","appName":"sasa"}': '' }

我可以解决这个问题,但我很想找出正确的方法来解决这个问题,我尝试在没有 JSON.stringify 的情况下发送我的状态,但我的 req 正文上什么也没有后端。我还尝试了一些其他的东西,但无法让它以正确的方式工作。非常感谢!

【问题讨论】:

    标签: json node.js reactjs superagent


    【解决方案1】:

    我的建议,

        // http request code... use XMLHttpRequest instead of SuperAgent
    
        let http = new XMLHttpRequest();
        http.open('POST','http://localhost:8080/guide');
        http.onload = ()=>{
            if (http.status >=200 && http.status <300){
                console.log(http.responseText);
            }
        };
        let state = this.state;
        http.setRequestHeader("Content-Type", "application/json");
        http.send(JSON.stringify(state)); // send state as payload
    
        // server.js in nodejs
        var express = require('express');
        var bodyParser = require('body-parser');
    
        var app = express();
    
        app.use(bodyParser.json({limit: '100mb'}));
    
        app.use('/guide', function(req, res){
            var payload = req.body; // payload varibale has your state object
        })
    

    在这个 server.js 中包含正文解析器,它负责您的请求正文并解析您的有效负载对象。

    【讨论】:

    • 谢谢,问题出在正文解析器上,我没有正确使用它。非常感谢!
    猜你喜欢
    • 2015-10-23
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2017-04-26
    • 2011-04-01
    • 2014-07-17
    • 2023-01-27
    • 2017-04-07
    相关资源
    最近更新 更多