Alamofire upload JSON response not compiling - javascript

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

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

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.

Meteor Files Storing a image url in Mongo collection

I'm really lost when it comes to file uploading in meteor and manage the data between client and server.
I'm using Meteor Files from Veliov Group to upload multiple images on the client side. They're getting stored in a FilesCollection called Images and I have my Mongo.Collection called Adverts.
collections.js:
Adverts = new Mongo.Collection('adverts');
Images = new FilesCollection({
collectionName: 'Images',
storagePath: () => {
return `~/public/uploads/`;
},
allowClientCode: true, // Required to let you remove uploaded file
onBeforeUpload(file) {
// Allow upload files under 10MB, and only in png/jpg/jpeg formats
if (file.size <= 10485760 && /png|jpg|jpeg/i.test(file.ext)) {
return true;
} else {
return 'Limit 10mb';
}
}
});
// if client subscribe images
if (Meteor.isClient) {
Meteor.subscribe('files.images.all');
};
// if server publish images
if (Meteor.isServer) {
Images.allowClient();
Meteor.publish('files.images.all', () => {
return Images.collection.find();
});
};
What I'm trying to achieve is, when I upload the images, I wanna store the URLs on the document in Adverts that I'm working with (I'm using iron:router to access those documents _id).
I managed to get the URL but only for the first image uploaded, my code for what I saw on the docs:
Template.imageUpload.helpers({
imageFile: function () {
return Images.collection.findOne();
},
myImage: () => {
console.log(Images.findOne({}).link())
}
})
Template.imageUpload.events({
'change #fileInput': function (e, template) {
if (e.currentTarget.files) {
_.each(e.currentTarget.files, function (file) {
Images.insert({
file: file
});
});
}
}
})
I was using a Meteor.Call to send the URL to the server, but I couldn't manage to update the document with a new property pic and the value url of the image
server.js:
imageUpload: (actDoc, imgURL) => { // actDoc is the document id that I'm working on the client
Adverts.update({'reference': actDoc}, {$set: {'pic': imgURL}})
},
This is probably a dumb question and everything might in the docs, but I've readed those docs back and forth and I can't manage to understand what I need to do.
The answer for my problem was to do it server side
main.js server
FSCollection.on('afterUpload'), function (fileRef) {
var url = 'http://localhost:3000/cdn/storage/images/' + fileRef._id + '/original/' + fileRef._id + fileRef.extensionWithDot;
}
MongoCollection.update({'_id': docId}, { $set: {url: imgUrl }}})

Uploading Avatar on Parse (using AngularParse Service)

{"name":"tfss-4dde4ec8-e678-495a-a5d0-d3e51f0bdafc-search-pic-img6.jpg","url":"http://files.parsetfss.com/d130ccda-cf9f-4264-999e-09305bed0fd1/tfss-4dde4ec8-e678-495a-a5d0-d3e51f0bdafc-search-pic-img6.jpg"}
This is the return Object, When I upload the file on the parse server. I want to use this object to store it on the Parse Class avatar column as type "file" not string. In short I am trying to store it as image file after uploading. I want to do it in Cloud Code javascript rather than on html javacript. I want to send the object to parse and store it as image file.
Here's my cloud code. I am new to parse a bit.
Parse.Cloud.beforeSave("editProfileweb", function(request) {
var avatar = request.object;
var user = request.user;
if (user) {
user.set("avatar",avatar);
user.save(null, {
success: function(user) {
response.success();
},
error: function(error) {
// Show the error message somewhere and let the user try again.
response.success();
}
});
} else {
response.error("User not authenticated");
} });
I guess this is what you are looking for
Object.set({columnName: {"name": File.name, "url": File.url, "__type": "File"}});

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