Parsing JSON in node.js gives an Error - javascript

My Node.js application reads a string, containing JSON data, from a Python backend using GET method. Sometimes when I use JSON.parse() and refresh the page after it succeeds, it gives an Unexpected token , error.
[
{
"postid":"c4jgud85mhs658sg4hn94jmd75s67w8r",
"email":"someone#gmail.com",
"post":"hello world",
"comment":[]
},
{
"postid":"c4jgud85mhs658sg4hn94jmd75s67w8r",
"email":"someone#gmail.com",
"post":"hello world",
"comment":[]
}
]
By console.logging the JSON object, I was able to verify that it only prints the object partially (meaning that only a part of the object was passed) when it gives the error - for example:
4hn94jmd75s67w8r",
"email":"someone#gmail.com",
"post":"hello world",
"comment":[]
}
]
or
[
{
"postid":"c4jgud85mhs658sg
In node.js, Im only using
var data = JSON.parse(resJSON); //resJSON is the variable containing the JSON

If it's succeeding "sometimes," I'd suspect you're parsing the response as the 'data' arrives, such as:
http.get('...', function (res) {
res.on('data', function (data) {
console.log(JSON.parse(data.toString()));
});
});
This will work if the response is sent all at once. But, it can also be divided into multiple chunks that will be received through multiple 'data' events.
To handle chunked responses, you'll want to combine the chunks back together and parse the response as a whole once the stream has come to an 'end'.
http.get('...', function (res) {
var body = '';
res.on('data', function (chunk) {
body += chunk.toString();
});
res.on('end', function () {
console.log(JSON.parse(body));
});
});

Related

Not getting a specified data from get request in json server when i use something else rather than id

i want to get a specific user from json-server with his email here's my json file
{
"Person":[
{
"id":1,
"name":"Bahy",
"email":"bahy#gmail.com",
"password":"kkk",
"phone":"0221223213",
"gender":"M",
"dateOfBirth":"4/11/1999",
"type":"A",
"carddata":{"cardNumber":"anything","cardexpiary":"anything","cvv":"anything"}
},
}
and here's my function
getPerson(email: string): Observable<IPerson> {
return this.http.get<IPerson>(`${environment.ApiRootLink}/Person?email=${email}`);
}
and here's the usage of this function
user:IPerson;
getPerson(email?email:"").subscribe((data)=>{
this.user=data as IPerson;
console.log(this.user);
});
so this function intead of giving me the object it gives me this output
so does anyone know what kind of problem here bec when i try the same http on postman it works fine

Alamofire upload JSON response not compiling

I'm doing an Alamofire upload to the server and want to decode some JSON that's sent back in response.
AF.upload(multipartFormData: { multiPart in
//do upload stuff to the server here
}, to: server)
.uploadProgress(queue: .main, closure: { progress in
//Current upload progress of file
print("Upload Progress: \(progress.fractionCompleted)")
})
.responseJSON(completionHandler: { data in
guard let JSON = data.result.value else { return }
print("JSON IS \(JSON)")
//decode the JSON here...
})
On the line where I'm guarding that data.result.value has a value (the JSON response sent from the server), I'm getting a 'Type of expression is ambiguous without more context'.
The code to send the JSON object from the server looks like this on the Node.js side:
app.post('/createCommunity', upload.single('cameraPhoto'), async function (request, response) {
// do operations to get required variables
var returnObject = {
community_id: id,
title: title,
members: members,
image: imageURL
}
response.send(returnObject)
}
Any ideas?
Since you already have a codable/decodable Community struct, try this approach:
AF.upload(multipartFormData: { multipartFormData in
//do upload stuff to the server here
}, to: server)
.responseDecodable(of: Community.self) { response in
debugPrint(response)
}

String to array of JSON object

I try to send data to my NodeJS server using HTTP protocol (vue-resource). I want to send a array of JSON object like this : [{"name":"Charlotte","surname":"Chacha","birth":"2000-04-02"},{"name":"Michael","surname":"Mic","birth":"1999-01-30"}].
My front code :
window.onload = function () {
var gamme = new Vue({
el:'#gamme',
data: {
myListe: []
},
methods: {
sendListe: function() {
this.$http.get("/NewListe?liste="+this.myListe).then(response=> {
if (response.body) {
console.log(response.body);
}
});
}
}
})
}
And my back code :
server.app.get("/NewListe", function(req, res) {
try {
let liste= req.query.liste;
console.log(liste);
} catch (e) {
console.log(e);
}
})
When I try to display the variable liste in the server side console, I obtain this : [object Object] . liste is a string type that I can't use. I would like to have an array of JSON, like in front.
I tried to parse like this JSON.parse(operationsGamme) , but I have this error : SyntaxError: Unexpected token o in JSON at position 1
You should surely be using a POST method if you are sending JSON data to the server - a GET just isn't designed for that sort of usage.
Since you have passed a JSON in the url, it will be URLEncoded. So, in the backend before you do JSON.parse(liste), you should do decodeURI(liste). decodeURI() will return the JSON string which you can parse and use it in your code. I hope this will fix your problem.

json content in response object in javascript returned from service worker

Sorry if trivial, or already asked, I can't find any question about that. I dont't know if I'doing right too...
I just beginned learning service workers:
I'd like to return some json object from a service worker for a specific request. N.B.: The code is just testing/learning code:
Service Worker Fetching Event:
self.addEventListener('fetch', function(event) {
if(event.request.url.indexOf("not_existing.json") > -1){
var obj = { "Prop" : "Some value" };
event.respondWith(
new Response(obj, {
ok: true,
status: 222,
url: '/'
})
);
}});
Fetch Call:
fetch('not_existing.json')
.then(function(responseObj) {
console.log('status: ', responseObj.status);
return responseObj.json();
})
.then(function (data){
console.log(data);
});
I know that the service worker catches the request, because on "console.log('status: ', responseObj.status);" I get "222", but the script breaks on "return responseObj.json();" with error "Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1"
If I return "plain text" from service worker, and read it with "responseObj.text()" all works great!
On this link "https://developer.mozilla.org/en-US/docs/Web/API/Response/Response" it seems I have only to write the body on Response constructor var myResponse = new Response(body, init);
What's wrong? How to specify the json response object?
You're not actually creating a response with JSON. The first argument of Response is a string or a few others, but not a random object. If you want JSON, you need to actually pass JSON, e.g.
var obj = JSON.stringify({ "Prop" : "Some value" });
The error you are getting is because currently it is converted to a string as
"[object Object]"
and
JSON.parse("[object Object]")
throws unexpected token "o".

ExpressJS why is my GET method called after my DELETE method?

In my express app, when the DELETE method below is called, the GET method is immediately called after and it's giving me an error in my angular code that says it is expected an object but got an array.
Why is my GET method being called when i'm explicitly doing res.send(204); in my DELETE method and how can I fix this?
Server console:
DELETE /notes/5357ff1d91340db03d000001 204 4ms
GET /notes 200 2ms - 2b
Express Note route
exports.get = function (db) {
return function (req, res) {
var collection = db.get('notes');
collection.find({}, {}, function (e, docs) {
res.send(docs);
});
};
};
exports.delete = function(db) {
return function(req, res) {
var note_id = req.params.id;
var collection = db.get('notes');
collection.remove(
{ _id: note_id },
function(err, doc) {
// If it failed, return error
if (err) {
res.send("There was a problem deleting that note from the database.");
} else {
console.log('were in delete success');
res.send(204);
}
}
);
}
}
app.js
var note = require('./routes/note.js');
app.get('/notes', note.get(db));
app.post('/notes', note.create(db));
app.put('/notes/:id', note.update(db));
app.delete('/notes/:id', note.delete(db));
angularjs controller
$scope.delete = function(note_id) {
var note = noteService.get();
note.$delete({id: note_id});
}
angularjs noteService
angular.module('express_example').factory('noteService',function($resource, SETTINGS) {
return $resource(SETTINGS.base + '/notes/:id', { id: '#id' },
{
//query: { method: 'GET', isArray: true },
//create: { method: 'POST', isArray: true },
update: { method: 'PUT' }
//delete: { method: 'DELETE', isArray: true }
});
});
** UPDATE **
To help paint the picture, here's the angular error i'm getting:
Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an object but got an array http://errors.angularjs.org/1.2.16/$resource/badcfg?p0=object&p1=array
I'm assuming that i'm getting this error because my delete method is calling my get method (somehow) and the get method returns the entire collection.
Server side
You're removing an element from a collection in your delete function. This is done asynchronously and calling your callback when it's finished.
During this time, other requests are executed, this is why your GET request is executed before your DELETE request is finished.
The same happens in your get function, you're trying to find an element from a collection and this function is too asynchronous.
But this is server side only and it is fine, it should work this way, your problem is located client side.
Client side
If you want to delete your note after you got it, you will have to use a callback function in your angular controller which will be called only when you got your note (if you need help on that, show us your noteService angular code).
This is some basic javascript understanding problem, actions are often made asynchronously and you need callbacks to have an execution chain.
Maybe try doing something like this:
$scope.delete = function(note_id) {
var note = noteService.get({ id: note_id }, function()
{
note.$delete();
});
}
Your code doesn't make sense though, why is there a get in the $scope.delete? Why not do as simply as following:
$scope.delete = function(note_id) {
noteService.delete({ id: note_id });
}
Error
I think you get this error because of what your server sends in your exports.delete function. You're sending a string or no content at all when angular expects an object (a REST API never sends strings). You should send something like that:
res.send({
results: [],
errors: [
"Your error"
]
});

Categories

Resources