Search code examples
jsonnode.jsreactjssuperagent

How to properly send JSON data using SuperAgent on React


I am sending the state of my react app to a server (not located on same as the frontend server).

        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);
            }
        });

The problem is at the receiving end (the backend server), I am getting the following on req.body:

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

I could work around the problem, but I'd love to figure out the right way to do this, I've tried to send my state without JSON.stringify but I can't nothing on the body of req at my backend. I also tried few other things but couldn't get it to work the right way. Thank you very much!


Solution

  • My suggestion,

        // 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
        })
    

    In this server.js contain body parser, that takes responsibility of your request body and parse your payload object.