get form data from '[object Object]' - javascript

I am passing uploaded file and dataObject in FormData:
let data = new FormData();
data.append("file", this.state.files);
data.append("data", formData);
formData is just a Json Object eg: formData = { "a":123 }
Passing data to the node server using put request with axios ,I am able to get the file object and data in req, but in data field it's giving '[object Object]'
Don't know how to access this. I tried JSON.parse(req.body.data), but getting error
SyntaxError: Unexpected token o in JSON at position 1

Looks like formData is an object that's cast to string [object Object] prior to being sent on the wire. Try data.append("data", JSON.stringify(formData)).

Send the object with JSON.stringify and then use JSON.parse once you receive data, to make the string object an object again.

Related

aws cloudwatch logs request.body as "[object Object]"

I am trying to log the body of an api request on Webiny api (they use fastify) but so far cloudwatch is outputting only "[object Object]".
I've tried:
console.log(request.body);
console.log(JSON.stringify(request.body));
console.log(JSON.stringify(request.body, null, 2));
Could this be how I am making the request?
function logData(payload: any) {
return navigator.sendBeacon('https://example.com/test', payload);
}
sendBeacon converts the payload to string.
An ArrayBuffer, a TypedArray, a DataView, a Blob, a string literal or object, a FormData or a URLSearchParams object containing the data to send.
navigator.sendBeacon('https://example.com/test', payload)
Just need to convert the payload to a string before sending it.
JSON.stringify(payload)

Can't access property from JavaScript object

I need to access properties from this object, but I am getting undefined.
I tried use JSON stringify and parse but without success.
console.log('ress', response.data);
console.log('ress data', response.data.url);
console.log('ress key', response.data.key);
output:
ress {"url":"my url","key":"my key"}
ress data undefined
ress key undefined
Probably your response.data object is a string, in this case you have to parse it into a JSON object to be enable to access the properties.
object = JSON.parse(response.data);
console.log('data url', object.url);

How to send formData object as key value pair in Vue js?

I am trying to upload an image with vue and laravel on backend. Everything was going well until I ran into a problem. My image gets sent when i make an axios call sending formData only as an argument.
let formData = new FormData();
formData.append("image", this.image);
axios.post('url',formData)
But on axios request I want to send an object, not just the formData, something like this:
const myObj={ name:'hello','shop_id':2, image:formData }
axios.post('url',myObj)
But this doesn't work. Is there any way I can work around with this?
Add the name and shop_id values to the FormData object. In this case FormData is the container in which you can send all of your data.
let formData = new FormData();
formData.append('image', this.image);
formData.append('name', 'hello');
formData.append('shop_id', 2);
axios.post('url',formData)
If your data becomes more complex and you need to send a big object with loads of data, then you could send the the object as a JSON value in one of the keys.
const complexObject = {
...loads of data here
};
formData.append('complexObject', JSON.stringify(complexObject))
Parse the JSON back to usable code on the server side to use the data inside the complex object.

OData returns array instead of JSON - How to convert?

I've been trying to figure how to properly receive an OData response in Javascript for a couple of days. The problem is the response is formatted as an array instead of JSON, so the function JSON.parse(mydata) does not work with the data I am receiving.
My question is two-fold: What is the proper way to request OData to send a response as JSON and/or how do I format my current response to be JSON?
Here is the code that I am using:
$.ajax({
type: "GET",
url: requestUri,
dataType: "script",
accept: "application/json",
success: function(data, request) {
var jsonData = JSON.parse(data);
},
error: function(msg) {
alert(msg);
}})
Here is an example response of logging the variable data with console.log:
{"#odata.context":"http://localhost:5001/odata/$metadata#Movies","value":[{"Title":"Pulp Fiction","Genre":"Action","RunTime":0,"Sales":0,"Key":2}]}
The problem is the response is formatted as an array instead of JSON
It can't be. You can't send "an array" over HTTP. You have to encode it somehow … e.g. as JSON.
jQuery will, unless you override it with the dataType option, use the Content-Type HTTP response header to determine how the data is encoded. If it is JSON, it will parse the JSON.
The value of data is what you would get if you read the raw responseText and passed it through JSON.parse.
So just don't try to parse it manually. jQuery has done it for you.
Skip the step:
var jsonData = JSON.parse(data);
… and just work with data.
NB: The output of JSON.parse is an object, array or other JavaScript data type. JSON data is what you get from JSON.stringify.
If the response is in OData format, as your example shows, but you want it in JSON format that can be parsed by JSON.parse, add $format=json to the OData query, so long as the OData endpoint supports it. I know Dynamics 365 does not.
You can add it to a variable and access it just like that.
var v={"#odata.context":"http://localhost:5001/odata/$metadata#Movies","value":[{"Title":"Pulp Fiction","Genre":"Action","RunTime":0,"Sales":0,"Key":2}]};
//v.value[0] is a json object
console.log(v.value[0]);
or skip the assignment altogether and access this way:
data.value[0]
data.value[0].Genre
data.value[0].RunTime
etc....

Send a file, a json object and a xml object in one call from javascript

The following shows what I want to achieve, but does not work:
BACKEND (Spring):
#RequestMapping(
value="/test",
method = RequestMethod.POST,
consumes = { "multipart/mixed", MediaType.MULTIPART_FORM_DATA_VALUE })
#ResponseBody
public String test(
#RequestParam("file") MultipartFile file,
#RequestParam("xmlObject") XmlObject xmlObject,
#RequestPart("jsonObject") JsonObject jsonObject) {
return "Done";
}
FRONTEND:
var multiPart = new FormData();
multiPart.append('file', file); //file is a File
multiPart.append('jsonObject', jsonObject); //jsonObject is a jsObject (auto converted by angular to json)
multiPart.append('xmlObject', xmlString); //xmlString is a xml-string
//... sendRequest with multiPart as data and Content-Type undefined -> becomes multipart/form-data; with a boundry
This gives a exception: Failed to convert value of type 'java.lang.String' to required type '...XmlObject'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [...XmlObject]: no matching editors or conversion strategy found" or Required request part 'xmlObject' is not present.
I tried using Blobs with content-type, but without success.
Also tried changing RequestParam to RequestPart and other values...
How to do this correctly?
(Btw, those calls are all working separately, but I need to bundle them to prevent a inconsistent state)

Categories

Resources