POST request via requestJS to send Array of JSON Objects and image files - arrays

I'm building REST API with NODEjs, using Express routers and Multer middleware to handle multiple body data and files.
My endpoint route 127.0.0.1/api/postData expects: json data with fields, one of which is array of json objects (I'm having nested mongoose schema) and 2 named images (png/jpg).
I need to send Post request via cURL with the following 5-object data structure:
name String
description String
usersArray Array of json objects like: [{"id": "123"}, {"id": "456}]
imgIcon Png/Image providing /path/to/imageIcon.png
imgHeader Png/Image providing /path/to/imageHeader.png
Any idea how to write this request with the help of request.js node http request library ?

Try the following:
request.post({
url:'http://127.0.0.1:7777/api/postData'
, formData: formData
, qsStringifyOptions : {
arrayFormat : 'brackets' // [indices(default)|brackets|repeat]
}
}, function (err, httpResponse, body) {
// do something...
}
I found three options for arrayFormat in https://www.npmjs.com/package/qs (used by https://www.npmjs.com/package/request):
'indices' sends in postbody: (this is the default case)
usersArray%5B0%5D%5Bid%5D=a667cc8f&usersArray%5B1%5D%5Bid%5D=7c7960fb
decoded:
usersArray[0][id]=a667cc8f&usersArray[1][id]=7c7960fb
'brackets' sends in postbody:
usersArray%5B%5D%5Bid%5D=a667cc8f&usersArray%5B%5D%5Bid%5D=7c7960fb
decoded:
usersArray[][id]=a667cc8f&usersArray[][id]=7c7960fb
'repeat' sends in postbody:
usersArray%5Bid%5D=a667cc8f&usersArray%5Bid%5D=7c7960fb
decoded:
usersArray[id]=a667cc8f&usersArray[id]=7c7960fb
these are three different ways to serialize arrays before posting. Basically it depends on the receiving end how these need/can be formatted. In my case it helped to use 'brackets'

Related

How to send state data to API which expects json gunzip file as payload (ex: sample.json.gz) in reactjs?

I have constructed a json data,
sample =[]; if (this.state.data) { console.log(this.state.data); this.state.data.map((Number) => { console.log(Number); Sample.push({ Number: Number, Attributes: { 'subAttribut': { Name: 'Name_ok', GroupName: 'GroupName_ok', }, }, }); }); }
I need to store this json data into a json file say sample.json,
then I need to gunzip it say sample.json.gz,
then I need to pass this file as a payload to an API in reactjs.
Or is there any other way to send this sample data as sample.json.gz file as payload to API
If you have access to any kind of backend serving this javascript client, the best solution would be to proxy your JSON through your own backend, gzip it there, and send it to the final destination.
If you must do it in the browser, you could try the Compression Streams API - But browser compatibility seems quite narrow still.
Edit: #ant Also pointed out this library https://www.npmjs.com/package/wasm-gzip

How do I retrieve data in localStorage for me to call in the axios request header?

This is my axios, how do I retrieve data in localStorage for me to call in the axios request header?
For example I want to get / post data to postman but we need a header to get the data:
import axios from 'axios'
export default axios.create({
baseURL: 'http://forexample/api',
headers: {
'timeout' : 30000,
'APP_TOKEN': 'forexampe',
'USER_TOKEN': JSON.parse(localStorage.getItem('data').data.DATA.TOKEN)
}
})
and this is a data request that I will send to Postman using the header
async componentWillMount(){
await API.post('url/api', this.state)
.then((response)=> {
let responJSON = response
})
console.log(this.state)
}
how do I retrieve data in localstorage for me to call in the axios request header?
for example I want to get / post data to postman but we need a header to get the data
and this is a data request that I will send to Postman using the header
From the docs:
The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings).
So the reason that you're not getting the result you expect is you're trying to access nested data as if it were a real JS object. This seems to be an issue with how you are storing the data, rather than how you are accessing it, as the localStorage.getItem('myKey') syntax you are using is ultimately correct. What you want to do is store only the single value you want to access as its own explicit key in the localStorage object and remove all of the dot notation you have after your getItem call.

Sending JSON and File in same multipart/form-data POST request

I have a form with an image and fields that I want to submit.
I'm running into problems since my POST request has content-type multipart/form-data and not JSON.
For example, any null values in my form are converted to "null" string...
Is it a bad practice ton send JSON and files in the same request ?
Perhaps I should decompose my POST in 2 seperate ones ?
One for the file in multipart/form-data
One for the JSON in application/json
To Expand #Mikkel's answer - you can write the following code to parse the JSON sent as string:
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.post('/multipart', multipartMiddleware, function(req, res) {
console.log('multipart API was called.');
console.log(req.body);
var bodyAsJson = JSON.parse(req.body.data);
console.log(bodyAsJson);
// some other multipart code...
});

Error 400 when POST'ing JSON in angularjs + Spark Single Page Application

I'm new to Single Page Application area and I try to develop app using angularjs and Spark framework. I get error 400 bad request when I want to post JSON from my website. Here is code fragment from client side:
app.controller('PostTripCtrl', function($scope, $http) {
$scope.newTrip = {};
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'http://localhost:4567/trips/add',
data : $scope.newTrip,
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
}
}).success(function(data) {
console.log("ok");
}).error(function(data) {
console.log("error");
console.log($scope.newTrip);
});
};
});
Values that are to be assigned to newTrip are read from appropriate inputs in html file. Here is server-side fragment:
post("/trips/add", (req, res) -> {
String tripOwner = req.queryParams("tripOwner");
String startDate = req.queryParams("startDate");
String startingPlace = req.queryParams("startingPlace");
String tripDestination = req.queryParams("tripDestination");
int tripPrice = Integer.parseInt(req.queryParams("tripPrice"));
int maxNumberOfSeats = Integer.parseInt(req.queryParams("maxNumberOfSeats"));
int seatsAlreadyOccupied = Integer.parseInt(req.queryParams("seatsAlreadyOccupied"));
tripService.createTrip(tripOwner, startDate, startingPlace, tripDestination, tripPrice, maxNumberOfSeats,
seatsAlreadyOccupied);
res.status(201);
return null;
} , json());
At the end I obtain error 400 bad request. It is strange for me that when I want to see output on the console
System.out.println(req.queryParams());
I get json array of objects with values written by me on the website. However, when I want to see such output
System.out.println(req.queryParams("tripOwner"));
I get null. Does anyone have idea what is wrong here?
I think the main problem is that you are sending data to your Spark webservice with the 'Content-Type' : 'application/x-www-form-urlencoded' header. Try sending it as 'Content-Type' : 'application/json' instead, then in your Java code declare a String to receive req.body(), you'll see all your data in there.
Note: When you try to acces your data like this req.queryParams("tripOwner"); you're not accessing post data, but you're seeking for a get parameter called tripOwner, one that could be sent like this http://localhost:8080/trips/add?tripOwner=MyValue.
I would advise using postman to post a request to your server and see if it works. Try a different content type too. Try using curl and play with the various headers you are sending. 400 suggests the wrong data is being sent or expected data is missing or the data is the wrong type but based on your code you've provided I can see nothing wrong (but see below).
When your server receives a request log all request headers being received and see what changing them does. If it works in postman then you can change your client code to mirror the headers postman is using.
Does your spark server validate the data being sent before your controller code is hit? If so ensure you are adhering to all validation rules
Also on looking at your code again your client is sending the data in the post data but your server is expecting the data in the query string and not in the post data?
What happens if your server just sends a 201 response and does nothing else? Does your client get a 201 back? If so it suggests the hook up is working but there is something wrong with the code before you return a 201, build it up slowly to fix this.
Ok, I managed to cope with that using another approach. I used Jackson and ObjectMapper according to Spark documentantion. Thanks for your answers.
You can see more about that here: https://sparktutorials.github.io/2015/04/03/spark-lombok-jackson-reduce-boilerplate.html
You're probably just needed to enable CORS(Cross-origin resource sharing) in your Spark Server, which would have allowed you to access the REST resources outside the original domain of the request.
Spark.options("/*", (request,response)->{
String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
if (accessControlRequestHeaders != null) {
response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
}
String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
if(accessControlRequestMethod != null){
response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
}
return "OK";
});
Spark.before((request,response)->{
response.header("Access-Control-Allow-Origin", "*");
});
Read more about pre-flighted requests here.

Send array of objects to RESTful API

How can I send an array (a set of simular items) in a POST request to a RESTful API build with Codeigniter?
I can send singular items like this:
name=John&email=demo#demo.com
But how can I send items like this and use them on the server side like an array?
keywords=blue,sky,weather,car,vacation
I would think you could send a json array depending on the capabilities of the backend. If the RESTful API consumes this content type you are able to then send an array by simply POSTing to the RESTful path, using the json array as the payload.
One way to send the payload would be with jQuery / AJAX:
.ajax({
url: "",
type: "POST",
contentType: "application/json",
data: JSON.stringify(jsonArray)
});
is it possible to send it in JSON?
{"keywords" : ["blue","sky","weather","car","vacation"]}

Resources