2014-07-14 53 views
9

Bazı json'ları ifade eden bir düğüm sunucusuna göndermeye çalışıyorum ama jsonun geçersiz olduğunu söylemeye devam ediyor. Ama onun değil, sadece eski bir nesne. Şu anda 'i beklenmeyen belirteç' hatası alıyorumgönderi json - geçersiz json

istemci:

$.ajax({ 
    contentType: 'application/json', 
    type: "POST", 
    url: "/admin", 
    data: {id: '435ghgf545ft5345', allowed: true} 
}); 

sunucusu: Ben de sonrası güzergahı ikinci parametre olarak bodyParser.json() koyarak denedim

var bodyParser = require('body-parser'); 
app.use(bodyParser({strict: false})); 

app.post('/admin', function(request, response) { 
    console.log(request.body); 
}); 

ve 'geçersiz json' ayrıştırma hatası 'olsun. Neden olduğunu anlayamıyorum.

cevap

10

Bu kod size yardımcı olabilir:

var jsondataResource = JSON.stringify({id: '435ghgf545ft5345', allowed: true}); 

$.ajax({ 
    type: 'POST', //GET or POST or PUT or DELETE verb 
    async: false, 
    url: '/admin', // Location of the service 
    data: jsondataResource , //Data sent to server 
    contentType: 'application/json', // content type sent to server 
    dataType: 'json', //Expected data format from server 
    processdata: true, //True or False 
    crossDomain: true, 
    success: function (msg, textStatus, xmlHttp) { 
     result = msg; 
    }, 
    error: ServiceFailed // When Service call fails 
}); 
function ServiceFailed(result) { 
alert('Service call failed: ' + result.status + '' + result.statusText); 
Type = null; Url = null; Data = null; ContentType = null; DataType = null; ProcessData = null; 
} 
+1

Hey Sambath, bunun için teşekkür öyleydi sunucu zaten çözümlenen nesneyi ayrıştırmak için çalışıyordu bu yüzden, benim json stringify olmadığını aslında. – wazzaday

+0

Büyük Hoşgeldin :) –

+6

Sadece kodun rasgele bir snippet'i göndermeyin. Bunun neden doğru olduğunu ve OP'nin neyi yanlış yaptığını açıklamanız gerekir. – dopatraman