2

Hi where to convert a json using node.js, to do it using body-parser with the code entered below: I am generated the error below. What is this error due to? how can I solve it? At the bottom I added the front-end java code for sending the json! The strange thing is that the -Note- field is not displayed in the request.body

Error --> console.log(request.body):

'{"Articoli":':
   { '{"Codice":"VAS-100","Descrizione":"SCHEDA DI ANALISI AD 1 INGRESSO \/ 1 USCITA ALLARME","Prezzo":"35.0"}': '' } }

Error  SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)

Node.js:

    const express = require("express");
    const myParser = require("body-parser");
    const http = require('http');
    const app = express(); 

    app.use(myParser.json());
    app.use(myParser.urlencoded({ extended: true }));
    //port
    const RunPort=8989;
    //server run on port
    app.listen(RunPort, function () {
        console.log("Server run on Port: ",RunPort);
    })

app.post("/rapportini/generarapportino", async function (request, response) {

    try {
        console.log(request.body);
        var data = JSON.parse(Object.keys(request.body)[0]);
        const ret = await RapportiniController.GeneraRapportino(data.Note);
        response.setHeader('Content-Type', 'application/json');
        response.send(JSON.stringify({
            return: ret
        }));
    } catch (err) {
        console.log("Error ", err)
    }
});

JSON:

  {
    "Note": "some note",
    "Articoli":[{
                    "Codice": "CodiceValue 1",
                    "Descrizione": "DescrizioneValue 1",
                    "Presso": "Prezzo 1"
                },
                {
                    "Codice": "CodiceValue 2",
                    "Descrizione": "DescrizioneValue 2",
                    "Presso": "Prezzo 2"
                }]
    }

Front-End Java Code(Android):

Generate JSON:

 String ret = "";
        try {
            JSONObject obj = new JSONObject();
            obj.put("Note", note);
            JSONArray objarticoli = new JSONArray();
            int size = articoli.size();
            int i = 0;
            System.out.println("\n Size of articoli: " + size);

            for (i = 0; i <
                    size; i++) {

                JSONObject artItem = new JSONObject();
                artItem.put("Codice", articoli.get(i).GetCodice().toString());
                artItem.put("Descrizione", articoli.get(i).GetDescrizione().toString());
                artItem.put("Prezzo", articoli.get(i).GetPrezzo().toString());
                objarticoli.put(artItem);
            }

            obj.put("Articoli", objarticoli);

            try {
                Database db = new Database();
                ret = db.RequestArray("/rapportini/generarapportino", obj, true);
            } catch (Exception ex) {
                System.out.println("\n Errore login Model");
            }

        } catch (Exception ex) {
            ErrorManagement.SendError("Errore: Generazione Rapportino: " + ex);
        }
        return ret;

Send of JSON:

String response = "";
        System.out.println("\n Sono in GetResponse con JSONOject: "+object);
        try {
            URL url = new URL("/rapportini/generarapportino");
            byte[] postDataBytes = object.toString().getBytes("UTF-8");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
            conn.setDoOutput(true);
            conn.getOutputStream().write(postDataBytes);
            Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (int c; (c = in.read()) >= 0; ) {
                sb.append((char) c);
            }
            response = sb.toString();
        } catch (Exception ex) {
            System.out.println("\n Errore funzione GetResponse class JSONRequest: "+ex);
        }
        return response;
11
  • What is your req.body? Commented Jun 11, 2018 at 7:10
  • You are sending wrong json from front-end Commented Jun 11, 2018 at 7:11
  • @CaptainJackSparrow this: { '{"Articoli":': { '{"Codice":"KSI4101000.300","Descrizione":"gemino Bus Scheda GSM\/GPRS (solo PCBA) solo per KS-BUS","Prezzo":"163.35"}': '' } } Commented Jun 11, 2018 at 7:11
  • Why JSON.parse(Object.keys(request.body)[0])? If you're getting JSON posted to you, I'd expect JSON.parse(request.body). Commented Jun 11, 2018 at 7:11
  • @T.J.Crowder I tried I always have the same error described above Commented Jun 11, 2018 at 7:13

2 Answers 2

1

First Use JSON.stringify then parse it to get desired output

var req={ '{"Articoli":': { '{"Codice":"KSI4101000.300","Descrizione":"gemino Bus Scheda GSM\/GPRS (solo PCBA) solo per KS-BUS","Prezzo":"163.35"}': '' } }

var data = JSON.parse(JSON.stringify(req));
Sign up to request clarification or add additional context in comments.

3 Comments

Ok for but if I do as you wrote: The NOTE field is not displayed anyway!
it will display.your request.body should have note field ..post request.body here
this is json with your code : { '{"Articoli":': { '{"Codice":"KSI4101000.300","Descrizione":"gemino Bus Scheda GSM\/GPRS (solo PCBA) solo per KS-BUS","Prezzo":"163.35"},{"Codice":"KSI6301000.310","Descrizione":"SIRENA PER BUS KS IMAGO AUTOALIMENTATA","Prezzo":"89.37"}': '' } } but if I check on jsonlint it tells me it's not properly formatted
1

You need to set correct Content-Type in Android application that is application/json

conn.setRequestProperty("Content-Type", "application/json");

and then accept in NodeJS application

app.post("/rapportini/generarapportino", async function (request, response) {

    try {
        const ret = await RapportiniController.GeneraRapportino(request.body.Note);
        response.json({
            return: ret
        });
    } catch (err) {
        console.log("Error ", err)
    }
});

6 Comments

request.body.Note is undefined
@riki Have you updated your Android code as I above mentioned ?
What is output of line System.out.println("\n Sono in GetResponse con JSONOject: "+object); ?
this is output: {"Articoli":[{"Codice":"AX 211A","Descrizione":"Feature-rich network camera with CCD sensor, delivers super","Prezzo":"705.0"}],"Note":"sa"}
You may refer stackoverflow.com/a/13988768/3461055 to know how to send json data in POST request
|

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.