León Diego
León Diego

Reputation: 33

Fetch API Error: SyntaxError: Unexpected end of JSON input

I'm working on this API and for any reason it returns me the message Error:

SyntaxError: Unexpected end of JSON input.

I'm doing MySQL-connection, in here everything is ok but, the problem appears when I try to do the POST request. My MySQL database is working at 100%.

CODE API

var express = require('express');
var router = express.Router();
var mysql = require('mysql');

router.post("/postPersona", MiddlewareMultipart, (req, res, next) => {
    //console.log("." + req.files.Src.path.split("public")[1]);
    //console.log(req.body);

    var query = 'CALL addPersonas(?,?,?,?,?,?)';
    var imgPath = "." + req.files.Src.path.split("public")[1];

    var datos =
        [
            req.body.Nombre,
            req.body.Telefono,
            req.body.Curp,
            req.body.ECivil,
            Number(req.body.Edad),
            imgPath
        ]

    conn.query(query, datos, (err, results, fields) => {
        if (err) {
            console.log("Error" + err);
            res.send(JSON.stringify("Error: " + err));
        }
        else {
            console.log(results);
            res.send(JSON.stringify(results[0]));
        }
    });
});

FRONT END JS

var Agregar = () => {
    var formData = new FormData();
    formData.append("Nombre", NomSrc.value);
    formData.append("Telefono", TelSrc.value);
    formData.append("Curp", CurpSrc.value);
    formData.append("ECivil", EstCSrc);
    formData.append("Edad", EdadSrc.value);
    formData.append("Src", ImgSrc.files[0]);

    var url = "http://localhost:3000/apiMYSQL/postPersona";

    fetch(url, {
        method: "POST",
        body: formData
    })
        .then((response) => {
            return response.json();
        })
        .then((data) => {
            console.log(data);
            alert(data);
        })
        .catch((error) => {
            console.log("Error: " + error);
        })
}

Console.log(result)

OkPacket { 
    fieldCount: 0, 
    affectedRows: 1,
     insertId: 0, 
     serverStatus: 2, 
     warningCount: 0, 
     message: '', 
     protocol41: true, 
     changedRows: 0 
    } 

Upvotes: 0

Views: 3223

Answers (2)

Abdeen
Abdeen

Reputation: 932

try using json instead of send, so modify the following:

res.send(JSON.stringify(results[0]));

to:

res.json({ results });

Hope this Helps!

Upvotes: 1

EmreSURK
EmreSURK

Reputation: 419

"Error: " + err is not a json object. It is not valid.

if (err) {
    console.log("Error" + err);
    //res.send(JSON.stringify("Error: " + err));
    res.send(JSON.stringify( {Error: err }));
}

And even simplier;

if (err) {
    console.log("Error" + err);
    //res.send(JSON.stringify("Error: " + err));
    //res.send(JSON.stringify( {Error: err }));
    res.json({Error: err });
}

Upvotes: 1

Related Questions