String to array of JSON object - javascript

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.

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)
}

Angular 10 | Http post | String array append FormData

I have to make a post request to an api endpoint, but I get an error status 500.
name: "HttpErrorResponse"
ok: false
status: 500
statusText: "Internal Server Error"
This is my code:
var selectedIds = ["31"];
let sendData = new FormData();
sendData.append('auth', this.dataService.REG_AUTH);
sendData.append('identifier', identifier);
sendData.append('selected[]', selectedIds);
this.http.post<any>('APIENDPOINT', sendData).subscribe(data => {
console.log(data);
}, error => {
console.log(error);
});
The issue is in this line: sendData.append('selected[]', selectedIds); I have no clue how to pass an array to FormData.
This is a working example from our android app. I need to convert this request in angular/typescript syntax:
#JvmSuppressWildcards
#FormUrlEncoded
#POST("APIENDPOINT")
fun addData(
#Field("auth") auth: String,
#Field("identifier") identifier: String,
#Field("selected[]") selected: ArrayList<String>
): Call<ResponseBody>
What I know so far:
It seems angular does not serialize the data, so I tried some hardcoded fixes, but none of these worked:
sendData.append('selected%5B%5D', '%2231%22');
sendData.append('selected%5B%5D', '31');
sendData.append('selected%5B%5D', 31);
sendData.append('selected%5B%5D', '%5B%2231%22%5D');
sendData.append('selected%5B%5D', selectedIds);
sendData.append('selected%5B%5D', JSON.stringify(selectedIds));
If I use selected instead of selected[], then I get no error, but obviously no data is updated, so I am pretty sure it is a serialization/parsing issue.
From this answer:
FormData's append() method can only accept objects of string or blob
type. If you need to append the array, use JSON.stringify() method to
convert your array into a valid JSON string.
formData.append('selected[]', JSON.stringify(selectedIds));
The statusCode 500 is the Internal Server Error, and it's the server-side problem. So, It's better to check the API if it can receive your request or not.
FormData's append() method accept string or blob type So you can use JSON.stringify() method (formData.append('selectedIds', JSON.stringify(selectedIds));). So try this:
let selectedIds = ["31"];
let sendData = new FormData();
sendData.append('auth', this.dataService.REG_AUTH);
sendData.append('identifier', identifier);
sendData.append('selectedIds', JSON.stringify(selectedIds));
this.http.post<any>('APIENDPOINT', sendData).subscribe(data => {
console.log(data);
}, error => {
console.log(error);
});

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".

Parsing JSON in node.js gives an Error

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));
});
});

Categories

Resources