0

I have a NodeJS Express API developed. I have a query and the respone of the query has to be send as nested response in the format mentioend below :

[
 {
  Status: Success,
  data:{
        "Key 1" : "Value1"
       },
       {
        "Key 2" : "Value2"
       }

  }
]

Key and value are obtained from mysql query which returns the response.

app.post('/getstatus', function(req, res){
    r1= req.body.imei;


    mysqlQuery = `SELECT value from table1 where key = true `;

    mysqlPool.query(mysqlQuery, function(error, response, fields){
        if(error){
            result = [{Status:"Error", Error: "Error Connecting to Database. Contact Administrator.", ErrorDetails:error.message }];

        }else{

            result=[{status:"Success", data:JSON.stringify(response)}];
        }
        res.json(result);
    });
});

I have tried the above code but it doesn't give me the response correctly. JSON.stringify(response) doesn't convert the data to JSON format.

2 Answers 2

1
else{

            result=[{status:"Success", data:response}];
        }
        res.json(JSON.stringify(result));
Sign up to request clarification or add additional context in comments.

2 Comments

Why you used 'stringify'? res.json(result); will work, I think.
Hey, good point! Docs on re.json here expressjs.com/en/api.html#res.json I didn't even look at OP's response method, just that they were using stringify in the wrong spot!
0

Donot stringify the response at server side. You should send it like a JSON and on user stringify it.

1 Comment

I think you're mistaking stringify for parse. Stringify makes a widely compatible string, and parse changes that into a JavaScript object. I'm not sure if the server can send a JavaScript object over http.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.