I am facing very strange issue here. I have a servlet running on my machine which renders my web page based on some input parameters.
Now, my screen capture with PhantomJS is not working if I try to send my data as a JSON object as a POST request type. For e.g. if I try:
Client side
var data = {"op": "get"};
page.open(address, 'POST', data, function (status) {
if (status !== 'success') {
console.log('[ERROR] :: Unable to fetch the address - ' + address + ", with data - " + data);
phantom.exit();
} else {
page.render(output);
}
console.log('processing...');
});
Server side
Now, on the server side, I am using Apache Velocity View templating so I have a single method which handles both get and post like :
public Template handleRequest(HttpServletRequest request, HttpServletResponse response,
Context context){
System.out.println(request.getParameter("op"));
//Always null
}
However, if I try sending my data from phantomjs as:
var data = "op=get&..."
It works
Also, at many places elsewhere in my code..I am doing Ajax POST requests to the same servlet and it works perfectly for all those request.
Would anybody explain why my servlet is not reading the JSON parameters passed from Phantomjs?
Servlets deal with simple request, so they only know how to parse (natively) HTTP parameters, either GET parameters from the URL, or POST parameters sent as application/x-www-form-urlencoded. Newer versions of the Servlet specification can also read multipart/form-data.
But there's nothing about JSON mentioned either in the Servlet or the HTTP specifications. So you must use a library that knows how to parse JSON and make the resulting object available in the Velocity context.
Related
I am working on an app that will submit data to a REST API and have some questions.
How does jQuery know if my post request was successful or not? Is it only looking at the HTTP status?
Is there a convention on what to return from a POST request to a REST API?
JavaScript
$.post( '/API/removeUser', { Eid: id }, function(data) { row.remove(); } );
PHP SLIM Framework
$app->POST('/API/removeUser', function () use ($app) {
// Get the ID from the jQuery post
$Eid = trim(stripslashes(htmlspecialchars($_POST['Eid'])));
echo json_encode(removeFunction($Eid));
});
Your backend should always return the appropriate HTTP status code along with the actual data. 404 for resources that were not found, 403 for unauthorized requests, 200 for successful requests etc. Most AJAX libraries (including jQuery) will rely on those for determining the result of the operation.
If you need more fine-grained error reporting, you could always include a field like "errorCode" in your response that contains an application-level error code that you define yourself and react to accordingly in your frontend code.
I'm currently trying to use an API and for the API, the developer console of that app asks the developer to submit a callback URL. Whenever the user of the app does something, it submits a GET request to the callback URL and I can retrieve data from that request. The current url I am using is https://appId:javascript-key=myJavascriptKey#api.parse.com/1/functions/receiveInfo. How can I handle the data, a.k.a the GET parameters, from the GET request? I found an answer on Parse.com that says how to retrieve data from a POST request, but all it says is that data = request.body. Do I do the same for GET requests and if so what do I do after that? Is request.body a json value?
Parse.Cloud.define("receiveInfo", function(request,response){
var params = request.body;//is this right to get the GET parameters they send? if so what do I do next?
});
The documentation has your solution at: https://parse.com/docs/cloud_code_guide#functions
For GET requests you have to use the request.params object which has all your request parameters for a GET are there. POSTS are sent in the request body, GET in the request parameters.
It looks like you are trying to get the params you can use something similar to:
Parse.Cloud.define("myMethod", function(request, response) {
if(request.params.myparam == "moo") {
response.success("Cow!");
}
else {
response.error("Unknown type of animal");
}
});
I tried to use Angular $http.post(url, data) method. But I am facing some problems to post correct data to server (WebAPI). I have tried follwing options but none is working.
var data1 = new Object();
data1.UserName = "UserA1";
data1.Password = "password123";
data1.ConfirmPassword = "password123";
var data2 = angular.toJson(data1);
var data3 = JSON.stringify(data1);
var data4 = { UserName: "UserA2", Password: "password123", ConfirmPassword: "password123" };
var data5 = "UserName=UserA3&Password=password123&ConfirmPassword=password123";
$http.post(url, data1)
$http.post(url, data2)
$http.post(url, data3)
$http.post(url, data4)
$http.post(url, data5)
None is working. What kind of data is correct for this method. I tried JQuery.post() with above data and it works. Its super strange for me why this simple angularjs method so hard to use or I am missing something.
Update:
Basically I am working on following example. I want to register user from client side (/api/Account/Register).
http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
This is because your server-side expects a request with its content x-www-form-urlencoded.
jQuery's $.post() sends the request with a Content-type of application/x-www-form-urlencoded whereas Angular's $http.post() sends the request with a Content-type of application/json (and also encodes the data as JSON (instad of form-data) if a JS Object is passed).
There are methods you can send x-www-form-urlencoded requests using $http (and there are several related answers on SO), but it involves less straight-forward code.
I suggest you change your server side to consume JSON requests.
Depending on what you have on server side, you should transform your request (that's the case for PHP, for example, or you can read from the input stream: php://input).
See this gist: https://gist.github.com/JensRantil/5713606.
If this is not solving your problem, please inspect the requests angular is creating (using the Developer Tools -> Network tab in Chrome for example), and tell us what you see.
I'm switching from jquery $.ajax, which was working fine, to using AngularJS $http.put to access a restful API.
I can make an API call, but the PUT data isn't getting sent - so my API sees a PUT request with an empty data object, which should contain a JSON string -> data.values = 'a json structure'
$http.put(
$rootScope.api_url,
{
values: jsonifiedValues
},
{
headers: {
apihash: sha256hash
}
}).success(function(data,status,headers,config){
// handle success
}).error(function(data,status,headers,config) {
// handle failure
});
I've not used AngularJS's $http before, but when I dump out the data in my PHP api it's just empty. this is how I'm pulling it from the request in the PHP:
parse_str(file_get_contents('php://input'), $put_vars);
$arr_req_data = $put_vars['values'];
In my API if the apihash sent from the request doesn't match the sha256 hash built on the PUT values, it fails.
This is working in JQuery, just failing now I've switched to $http. I'm not sure why the PUT data seems to be empty.
The return value from file_get_contents('php://input') will be a JSON string (provided everything got sent), so parse_str is not the right function to handle that data.
Instead use json_decode.
Also there is no need to send jsonified values, it will just make things more complicated as you'll have to use json_decode twice.
I have a javascript variable that I want to pass back to the server side, which I thereafter intend to use it as an access token to grant user access to other pages which requires this token.
I wonder how do I pass this javascript variable back to server, so I can set it to a session variable? Do I need to send it back using ajax?
this is the part of jQuery I use to retrieve the token from server
$(document).ready(function () {
$('#loginForm').submit(function(e) {
var blargh = $(this).find('input').serialize();
$.ajax({
type: 'post',
url: '/WebAPI/api/authenticate/login',
data: blargh,
success: function (data) {
$.each(data, function(index, token) {
$('#container').prepend('<input type="hidden" name="MY_HIDDEN_FIELD_NAME" id="MY_HIDDEN_FIELD_NAME" value="'+token+'">');
});
},
error: function(jqXHR, status, errorThrown) {
alert("Error " + status + "\nError Thrown" + errorThrown )
},
});
e.preventDefault();
});
});
To pass back an additional item in the AJAX POST, you could add it like this...
var blargh = $(this).find('input').serialize();
blargh.someItem = "value";
Bear in mind that this only works when the form is submitted using AJAX, so not where JavaScript isn't available or is disabled.
All the normal security disclaimers apply!
I would recommend sending you the acess token in request headers when u are sending a ajax request
xhr.setRequestHeader('custom-header', 'value');
and on the server side you can fetch the request header
Couldn't you pass it back as either a hidden form element or pass it back in the query string of a ajax postback?
Example of a hook to get the post back value in global.asmx
protected void Session_Start(object src, EventArgs e)
{
if(!string.IsNullOrEmpty(Request.Form["MY_HIDDEN_FIELD_NAME"]))
{
Session["MY_SESSION_NAME"] = Request.Form["MY_HIDDEN_FIELD_NAME"]
}
}
First - why is your client generating the token (I hope I've understood you correctly there)? The server should generate the token and the client must then be responsible for maintaining it.
If it's an API token that'll only ever be used in the browser from javascript, then I recommend using an authentication cookie - all browsers know how to handle them and you can also easily expire them server-side if you no longer want to allow a particular token to have access (that's quite an important point). Also I strongly recommend against relying on server-side session to maintain the authentication session.
Authentication tokens should ideally be stateless (just like in Forms Authentication's cookie) - the burden of proof is on the client to send you a correct token, with that token containing the information you need to re-initialise the current requests state with the correct user.
If, however, it's a general purpose API for any type of client then you should allow the client to send the token to you in the query string of all requests at a very minimum. You should also support taking it in the request header as well - clients that can easily support setting request headers often prefer to because it then hides the auth token from the URL and makes formatting requests easier (there's also the potential to max out a web server's query string limit if the token is big enough).
I then recommend you look, at a minimum, at overriding MVCs AuthorizeAttribute (there are 2 - one for the 'standard' MVC 4 pipeline and one for the new Web API pipeline, & they would both need to be done if you are using both technologies. The link is for the MVC 4 one) to crack out your cookie/header/query string value. In there you can get the value, decrypt the token, identify the user and set the roles. The core code of that attribute then contains the logic for denying a request based on whether the user is authenticated/has a certain role/is a certain user.