Pros and cons of parameterizing angular request - javascript

I'm a full-time backend developer just starting to learn angular for some of my own projects.
By default it seems angular $http requests are sent as JSON strings. I am currently overriding the transformRequest method to parameterize it like jquery. Its more convenient for my backend framework (Phalcon PHP) to receive it this way.
Before I commit to this path, are there any cons to structuring it this way? Any problems unit testing or using third-party modules?
Edit
To clarify, angular sends POST as JSON string in the body. jQuery and other frameworks I've used send as form-urlencded like:
Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21
http://en.wikipedia.org/wiki/POST_%28HTTP%29#Use_for_submitting_web_forms
Which, perhaps due to the content header populates the $_POST global in php (I assume) with the form data;

I would recommend you to stick to the JSON format and send data in JSON request body instead of key=value param pairs. You can receive JSON cleanly with Request::getJsonRawBody() in Phalcon.
The main difference is that POST vars format allows you to send key=value pairs of data. When it comes to more complex structures (arrays, associative arrays, nested objects and so on), you will start to have problems which you will have to solve some way. It won't happen if you send JSON objects in POST/PUT request bodies. And, of course, you get serializing and deserializing OOTB in both AngularJS and Phalcon.
You should strongly consider key=value params for GET parameters only and JSON data for everything else. Obviously, you can mix those two (I mean i.e. sending new content for your article as PUT request with JSON body, but specifying article id in URL like /article?id=123).
You may be also istresed in reading REST API: Request body as JSON or plain POST data?.

Related

Is it safe to make a POST request with JSON data using ajax?

I'm working on web application where I need to send some data using ajax with post method. So I have two choices to send data whether in JSON format or query prams. I'm confused which should I use? and is it safe to send data in JSON format?
As #lucasreta mentioned, if you use HTTPS, it doesn't really matter either way.
Both methods are widely used. I know that Google accepts a Post request with query params and responds with a JSON object for ReCaptcha Server side validation.
Sometimes, the decision to use one or the other (or both) is dependent on how easy your chosen back-end technology makes it for you to either parse out query params or serialize JSON.
I will say that there is a general trend in using JSON in the request body as opposed to query params.
I found a couple of SO questions that are more down the lines of what you are asking...
REST API Best practices: args in query string vs in request body
REST API Best practices: Where to put parameters?

Is there any way to send an arraylist of int elements from javascritp to spring contoller without using Json?

I have a list of int elements inside a javaScript code, so I want to send this list to a spring controller
The API will generally simply return raw data back to the client – XML and JSON representations usually – and so the DispatcherServlet bypasses the view resolvers and returns the data right in the HTTP response body.
https://www.baeldung.com/spring-controllers
Basically, what this is saying is you can use XML (which is somewhat common), but I believe other datatypes are possible, as long as you account for them on both sides.
Just use:
myMethod(#RequestParam("value1") List<Integer> valueOne)
in your Java and send it however you want in your JavaScript (as long is it's documented in Spring)
And you can cast that into whatever. But as far as I know you it's advised to pass it as either XML or JSON.

Sending files while using Content-Type:application/json

i am passing data from the client to the server (WebAPI or MVC) as a pure json as the http post body while using Content-Type:application/json.
it works great but now i need to add to the same post request a file which the user may need to add to that http post.
As per my understanding i can not use formData object because i can not mix the body with json and the formData.
i thought about using FileReader javascript function and pass the encoded string as one of the json properties but it smells as a "bad practice".
is there a better way to do so?

Write JSON data from front-end to back-end in nodejs

I have ButtonClick.js and TakeData.js files. I defined my json data in TakeData.js as below
var dataObj = {};
var locationsObj = "locations";
dataObj[locationsObj] = {};
dataObj[locationsObj].source = [];
dataObj[locationsObj].target = [];
When I click the button in ButtonClick.js and the code snippet as below
button()
.container(g2)
.text(text2)
.count(1)
.cb(function()
{
console.log(dataObj[locationsObj].source[0]);
console.log(dataObj[locationsObj].source[1]);
console.log(dataObj[locationsObj].target[0]);
console.log(dataObj[locationsObj].target[1]);
console.log("SaveFile");
})();
I want to send json data into the nodejs file writing function as the following.
fs.writeFile('sample.txt', [need to insert my JSON], function(err) {
if(err) return console.log(err);
console.log('Hello JSON > sample.txt');
});
How can I do that? Is there another effective way?
Your backend needs to have an HTTP server listening on some port that is accessible to your frontend. Then your frontend needs to make an AJAX request to your backend (most likely a POST request) and send the required data in the request body.
Now, your backend needs to handle the request, get the data and write it to the file or do whatever you want with that.
Things to keep in mind:
use body-parser if you're using Express
remember about CORS
It's easier if you use a higher level framework on the backend like Express, Hapi, Restify, LoopBack etc. instead of the low level http module in Node.
It's also easier if you use a framework on the frontend like jQuery, Angular, React, Aurelia, Ember etc.
The first step is to set up a RESTful POST operation (an HTTP POST) on your server. This is the typical service mechanism for what is sometimes called an AJAX call. Once you have the server set up to receive a string via the POST, you can serialize your objects on the client side and deserialize (reconstitute) the objects on the server side.
To serialize, you can use stringify on the client side. A simple web search for "stringify" will show you different ways to use stringify in a browser-independent, backward compatible way.
stringify(obj)
On the server side, node.js has a global JSON object. Use parse to reconstitute an object or objects from the string. Other major languages now have similar parser methods. 1
JSON.parse(strJSON)
To get started, you can test the mechanism with just one simple object. Then you can aggregate the objects in a JSON array or associative array and send them all at once in a single POST.
[1] There are frameworks that encapsulate this process, but it may be of value to you to NOT initially use them so you get a clear picture of the mechanics of a RESTful POST over the HTTP protocol. It is the key thing that a browser does when you submit an HTML form, and RESTful operations are key communications elements in today's IT world.

using backbone to put data into rest server

I have a question.
If i have a model named Input. It contains model Invoice and Collection InvoiceDetailCollection.
I modified the backbone.js specifically create:"POST" into create:"PUT" inorder to allow PUT since my service doesn't use POST.
If i were to use Input.save() What should my server expect as a request? I mean already have set a service method to expect string since if i expect string i can't use the input.save();
What should be the right parameter i should expect on my server side if i were to use the Input.save() method of backbone.js
By default, Backbone sends application/json data and the server should expects JSON data. You'll want to decode it. I use PHP and middleware that automatically json_decode($data) and turns it into an associative array for me to manipulate.
If this isn't possible, (can't take JSON data) I think what you want is to use emulateJSON It will serialize your data and send it as application/x-www-form-urlencoded like an HTML form.
http://documentcloud.github.com/backbone/#Sync-emulateJSON

Categories

Resources