2015-09-07 1 views
3

Hey j'essaie d'envoyer mon entrée ajax json à mon serveur, mais cela ne fonctionnera pas.Noeud js ne peut pas analyser stringson json

à l'envoi du JSON (de chaîne de caractères) à mon serveur, mon serveur est pleurais de: SyntaxError: Fin inattendue de l'entrée à Object.parse (natif)

Mais quand je suis envoyer le même JSON via Postman, aucune erreur n'apparaît.

Mon ajax:

 $.ajax({ 
 
      method: "POST", 
 
      url: "/new", 
 
      data: {ort: park[0], activity: activity, datum: date, teilnehmerzahl: teilnehmerzahl, schwierigkeit : schwierigkeit, dauer : dauer, time : time, treffpunkt : treffpunkt}, 
 
      dataType: "json", 
 
      success: function (data) { 
 
       alert(data); 
 
      } 
 
      , error: function (jqXHR, textStatus, err) { 
 
       alert('text status ' + textStatus + ', err ' + err) 
 
      } 
 
     });

JSON typique de chaîne de caractères:

{"ort":"Bayerischer Wald","activity":"Klettern","datum":"17.09.2015","teilnehmerzahl":"2","schwierigkeit":"Anfänger","dauer":"1h","time":"12:00","treffpunkt":"Hier"}

Mon client:

app.post('/new', jsonParser, function(req,res){ 
 
    var test = JSON.stringify(req.body); 
 
    fs.readFile('./views/neueGruppe.ejs', {encoding: 'utf-8'}, function(err, filestring){ 
 
     if(err){ 
 
      throw err; 
 
     } 
 
     else{ 
 
      var options = { 
 
       host: 'localhost', 
 
       port: 3000, 
 
       path: '/new', 
 
       method: 'POST', 
 
       headers: { 
 
        'Content-Type': 'application/json', 
 
        'Content-Length': test.length 
 
       } 
 
      } 
 

 
      var req = http.request(options, function(response) { 
 
       response.on('data', function (chunk) { 
 

 
       }); 
 
      }); 
 

 
      req.on('error', function(e) { 
 
       console.log('problem with request: ' + e.message); 
 
      }); 
 

 
// write data to request body 
 
      req.write(test); 
 
      req.end(); 
 
     } 
 
    }); 
 
});

Mon serveur:

rest.post("/new", jsonParser, function(req,res){ 
 

 
    var data = {users: 
 
     [ 
 
      {id: 1, name: "Peter"}, 
 
      {id: 2, name: "Jessica"} 
 
     ]} 
 

 

 
    console.log(req); 
 
    res.json(data); 
 

 

 
});

Quand je change le type de contenu sur mon client de JSON au texte, aucune erreur apparaît, mais aucune donnée a été envoyé soit. Son seul passe lorsque je tente de l'envoyer comme JSON, mais même dit jsonlint que son JSON valide ...

Répondre

3

Utilisez la méthode JSON.stringify pour envoyer la demande correcte.

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.

Syntax

JSON.stringify(value[, replacer[, space]])

Source: Mozilla Contributors

JSON.stringify() convertit une valeur en notation JSON

$.ajax({ 
 
    method: "POST", 
 
    url: "/new", 
 
    contentType: 'application/json; charset=utf-8', 
 
    data: JSON.stringify({ort: park[0], activity: activity, datum: date, teilnehmerzahl: teilnehmerzahl, schwierigkeit : schwierigkeit, dauer : dauer, time : time, treffpunkt : treffpunkt}), 
 
    dataType: "json", 
 
    success: function (data) { 
 
     alert(data); 
 
    }, 
 
    error: function (jqXHR, textStatus, err) { 
 
     alert('text status ' + textStatus + ', err ' + err) 
 
    } 
 
});

2

Pour envoyer correctement votre JSON dans le corps de demande, utilisez JSON.stringify:

 $.ajax({ 
 
      method: "POST", 
 
      url: "/new", 
 
      contentType: 'application/json; charset=utf-8', 
 
      data: JSON.stringify({ort: park[0], activity: activity, datum: date, teilnehmerzahl: teilnehmerzahl, schwierigkeit : schwierigkeit, dauer : dauer, time : time, treffpunkt : treffpunkt}), 
 
      dataType: "json", 
 
      success: function (data) { 
 
       alert(data); 
 
      } 
 
      , error: function (jqXHR, textStatus, err) { 
 
       alert('text status ' + textStatus + ', err ' + err) 
 
      } 
 
     });

Plus d'informations peuvent être trouvées ici: jQuery posting valid json in request body