how to use javascript in jmeter - javascript

how to use javascript when I send request to server and get response as JSON data. Then I need to use response data for check condition in javascript (JSR223 Sampler) in Jmeter and return data for new http request

JMeter is not a browser hence it cannot execute client-side JavaScript. However it is capable of recording and replaying JavaScript-drivern HTTP requests so it is possible to send a request to the server.
You can use JSON Path Extractor or JSON Path Assertion (both available via JMeter Plugins) to extract certain bits of JSON response or to check it.
See Using the XPath Extractor in JMeter guide (scroll down to "Parsing JSON") for plugin installation instructions and some form of JSONPath language reference.

Related

send data to json file with javascript fetch api

i have one empty json file. I want to add json data to my json file when button is clicked. but it gives error 405. how can I do?
error:
POST net::ERR_ABORTED 405 (Method Not Allowed)
code:
var data={
method:"POST",
body:{
userId:1,
title:"sample title",
body:"sample body"
},
headers:new Headers({
'content-type':'application/json',
'dataType': 'json'
})
}
fetch("anaveri.json",data).
then(res=>{
console.log(res);
}).
catch(error=>{
console.log(error);
});
The browser isn't able to directly write data to the server's file system.
It would be a horrible security problem if it could. Google's homepage would get overwritten with some different bit of trolling every few seconds!
The browser can send an HTTP request to a URL. The server then needs to use server side programming to process that request.
You need to pick a programming language that your server supports (or change servers to one that supports your server-side language of choice) and write a webservice that takes the data from the request and stores it.
You could have it write directly to a JSON file, but that risks "fun" problems with concurrent writes so it is more typical to store the data in a database and have another webservice generate the JSON on demand.
You should consider adding some sort of tests (e.g. password authentication and data validation) to control who can insert new data and what sort of data they can insert to avoid the aforementioned vandalism problem.
Client-side scripting isn't allowed to change files on the server or the local file system for security reasons. Depending on what you're trying to achive, you need to do one of these things:
Send your data to your server via POST and your server does the saving
Create the file contents blob and download it
Use the browser's FileSystem API instead of the client one's
405 (Method Not Allowed) means that the resource you're querying (in this case, your json file) does not implement the method you're trying to use on it. In order to add information to your json file, you need to have some sort of a backend logic that implements a RESTful API, so that you can issue requests using JavaScript - you can't just do it with JavaScript alone.

Html vs JSP - get request header token value

I am working on Java application . Front end would be Angular2 .
If I try to open my application home page( index.html is configured in web.xml as default page ) . Access URL should be http://localhost:8080/MyWebApp .
Then I have taken into an standard organization's login page for authentication. If authentication succes , HTTP Authorization token will be set in the request header and finally control comes to display my application home page.
If I use jsp, I can get request header as,
String authHeader = request.getHeader("authorization");
out.println("<h2>HTTP Authorization header:</h2>");
if (authHeader == null) {
out.print("No authorization header");
} else {
out.print("<textarea readonly id='authHeader' rows=\"5\" cols=\"80\">" + authHeader + "</textarea>");
}
But we are using html as front end, because of angular 2 .
So for my scenario, how I can I get the request header and token.
Please don't hesitate to edit my question, if it is not clear.
You can't get a value of a header from client-side JavaScript. The only exceptions are the User-Agent and Referrer headers, because the browser provides the values in the document and navigator objects.
You said you are working on a Java application with an Angular 2 front end and some other application provides a token (might be useful to specify if this is something standard, e.g. OAuth2). I will assume that it is a custom token. I believe you also meant you have some server side component, a servlet.
What you can do is to implement the authentication using the servlets (or even JSPs) and then redirect back to the Angular 2 front end application, passing the token in the URL as a query parameter. URL is easy to read in Angular 2. However this is not very secure, even if you use something like JWT. As an alternative to URL, you can use the Set-Cookie header and then read the cookie from Angular.
What would be almost secure would be to authenticate the user using the server side (servlet or even JSP). Then create a one-time token which is passed in the URL as a query parameter when redirecting to your HTML page. Then use the one-time token in a call to the server again to retrieve the real authentication token using a proper REST call from Angular 2 with request and response.
Depends on how much control you have and what kind of authentication the auth application uses, you might want to take a look at the OAuth2. It deals with plenty of different authentication scenarios. Specifically the OAuth2 implicit grant flow is used to authenticate users from client-side only applications. Even if you can't use that, it will give you some ideas.
When you are using a server-side authorization, your server put headers with authorization to your HTML pages. But also you can put this tokens to your page response by meta tags at server side. And then access to meta tags by js.
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
Meta tags are similar to response headers and can complete or override response headers.
Read this post please Spring Security CSRF Token not working with AJAX call & form submit in same JSP
You can handle this at server side(JSP's expressions work on server side), create a handler method on server where you can check header and then redirect to your Angular App.
I think we can use HTTP HEAD method as JQUERY AJAX request in your HTML page .
https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
The HEAD method asks for a response identical to that of a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.
ajaxRequest = $.ajax({
type: "HEAD",
async: true,
url: 'index.jsp',
success: function(message){
var headerValue =ajaxRequest.getResponseHeader('Content-Length')]);
}
});
There are various way to solve this issue as I faced it a lot before and what I prefer is;
When authentication is completed in login page and a token generates I store it into HTML storage, make be in localStorage.
The main point you should understand that your views should not be accessed directly and there has to be a authentication (or may be a authorisation) step(s) before accessing the page(view).
So what you can do is set a URI for accessing any page, consider that is;
http://host/appname/pageName
And when you connect with this URI via ajax call add the token that is stored in localStorage in headers. And check all authentication and authorisation works and if success return the view(as the pageName suggested in the URI), else return the login view.
If i understand you correctly,
Angularjs is a client side framework and is intended to run inside a browser without any intervention of server by reducing its load by serving the application logic
All operations that need to be performed by angular will only be initiated at client side by the browser after loading the HTML and javascript.
The scope of angular is only limited to that area any way it is not a disadvantage it is the actual intention of client side frameworks.
Regarding request response headers you can only have access to headers of AJAX request
Following are the solutions to these problems:-
If you are using tomcat or any servelet container in order to serve the application or hosting angular code you can use JSP insted of HTML,since JSP is processed to html by the servelet container before passing it to client side.I think this solution will work in your case based on my inference form your question
Otherwise configure servelet that process the success and failure handlers from the authentication server and from angular you need to poll the servelet for getting the request header value.

JavaScript: list files from http

Can i retrieve a list of files that are located in a URI (HTTP Server) from JavaScript? I only find methods that rely in server side scripting (ie, get the list from a php that reads and outputs the file list accessing the filesystem)
If you store that list in a single file or you know all the locations you want to check, you can use an AJAX request on the client side to make a HTTP request and subsequently load data from your own server.
If you are pulling data from a domain that differs from the one serving the page which runs the AJAX request, then you will run into a problem with your "Cross Origin Request" which will likely prevent you from implementing this feature.
In general http not pass files. it pass information.
You send request and receive answer.
For example:
if you go to the site:
http://www.example.com/index.html
the server receive request with route and it decide what to do with it.
The server can response with index.html file but it can response also with a picture file or another information.
if you want you can read the http protocol
https://www.rfc-editor.org/rfc/rfc2616
or in wikipedia
If you want you can save all your data in one json file and request this information from the server. Another way is to use ftp..

Google Geocoding ajax request with Yahoo YUI 3

I understand the way to make an ajax call in YUI 3 is using the IO utility.
I want to get the address of a location from Google's geocoding API.
<script type="text/javascript"><!--
YUI().use('io-base', function(Y) {
function complete(id, o) {
var data = o.responseText; // Response data.
alert(o.responseText);
};
Y.on('io:complete', complete, Y);
var request = Y.io("http://maps.googleapis.com/maps/api/geocode/json?language=en&sensor=false&latlng=12,34);
});
//-->
</script>
I get a reply with method OPTIONS and status code 405 Method Not Allowed.
I believe this is because of some "preflight" permission check. I do not receive the desired response. If I copy and paste the url into the browser, I see the json data.
I could post the ajax request to a php script on my own domain and get the json response with curl.
But why have this extra step if I could just get the data in javascript?
So what can I do to solve this? Is the IO utility not the right library to use?
You're making a cross-domain XHR request, and running into the "Same origin policy", a generic restriction in client-side JavaScript. See for example Why do I still receive 405 errors even though both URLs are from XXXX.com?
There are various ways to work around this problem:
1) Make a server-side request in PHP, as you suggest
2) Use the YUI jsonp module
3) Use the YUI YQL module, which proxies your request through Yahoo! servers and handles JSONP housekeeping for you
There are many other ways to tackle this problem, but those three should get you started.
Y.io has support for cross domain requests. See http://yuilibrary.com/yui/docs/io/#cross-domain-transactions
You need to properly config it with the "xdr" property, and load the "io-xdr" module, etc. This example uses it as well: http://yuilibrary.com/yui/docs/io/weather.html

using oembed - json responses (in client side javascript)

If an oembed provider is only outputting json and xml, does that mean it is impossible to use this via client side javascript? ($.ajax request to the provider)?
Can we only use oembed providers that allow for a jsonp callback in javascript?
Thanks,
Wesley
you cannot use ajax across different domains.
Jsonp is an option, other option is to have a server side script which will fetch the data from the provider and then make an ajax call to that script to return the fetched data

Categories

Resources