Better ways of catching Request and Response Headers? - javascript

Im currently working in MVC and I have what I see as crude ways of catching response and request headers on my pages.
First is Response headers which I currently handle on the page
$(document).ready(function () {
var name = "Comp";
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var myHeader = req.getResponseHeader(name);
alert(myHeader);
});
it makes a new request when the document is ready which could ruin the header if it isn't pretty static (wouldn't work if the header were to change between the sessions) but it currently workes.
I do catch the Request header inside of the controller
public new ActionResult Profile()
{
var head = Request.Headers.GetValues("Comp");
try
{
if (head != null)
{
string id = head.First();
ViewBag.message = head.First(); //controll
return View();
}
}
catch
{
ViewBag.message = "Header method Failed";
}
return View();
}
Now I wonder if there are better ways of doing this. Someone enlighten me.

Related

Running process after getting files in controller using Request.Form.Files

I've got a problem in my ASP.net Core application. I use MVC. I send a file from js to controller using:
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Test/Sing", true);
xhr.send(fd);
then I got it in controller action:
[HttpPost]
public IActionResult Sing()
{
var file = Request.Form.Files[0];
byte[] filedata = null;
using (var target = new MemoryStream())
{
file.CopyTo(target);
filedata = target.ToArray();
}
\\some filedata processing
return RedirectToAction("Question");
}
The filedata is something that I need to process and then redirect to another action. When I put a breakpoint at the end of using (MemoryStream) I can see that the filedata is filled with data I need but when I want to redirect to action nothing happens. It looks like a process with the xmlhttprequest is still running on the client side and waiting for response. Am I right? How to get the file, cut the process, perform some file processing and be able to redirect to another action?
You should manually handle the redirect using window.location.href in success callback function of ajax/XMLHttpRequest .
If using XMLHttpRequest ,you can add listener for load events ,the listener must be added before the send() function:
function reqListener () {
window.location.href = "url";
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();
If using AJAX redirect in success callback function :
success: function (response) {
window.location.href = "url";
}
Controller :
return Json("ok");
//Or return the url
return Json(new { redirectToUrl = Url.Action("action", "contoller") });

Utilize same http session in javascript through many requests

In my backend I authenticate user once inlogging and then store the authenticated sessions at the server. Then after each user's request i check if the session associated with a request is stored as authenticated. The problem is that when I use JavaScript requests a new HTTP session is used each time i send something to my server written in Java.
When I use Postman everything is okay because it stores session through many requests.
//Here is authentication on server side - it works fine
#CrossOrigin
#RequestMapping(value= "/login", method = RequestMethod.POST)
public #ResponseBody String login(#RequestBody Account retrievedAccount,
HttpServletRequest httpServletRequest) {
if (retrievedAccount != null) {
Account account =
accountDAO.getAccountByLogin(retrievedAccount.getLogin());
if (account != null &&
account.getPassword().equals(retrievedAccount.getPassword())) {
this.registeredSessionsContainer.add(httpServletRequest.getSession());
return new ResponseEntity(HttpStatus.OK).toString();
} else {
return new ResponseEntity(HttpStatus.UNAUTHORIZED).toString();
}
} else {
return new ResponseEntity(HttpStatus.UNAUTHORIZED).toString();
}
}
Here is a simple way to check if a session is already authenticated:
#CrossOrigin
#RequestMapping(value= "/checkLogon", method = RequestMethod.GET)
public #ResponseBody String checkLogon(HttpServletRequest
httpServletRequest) {
if(this.registeredSessionsContainer.
contains(httpServletRequest.getSession()))
return new ResponseEntity(HttpStatus.OK).toString();
} else {
return new ResponseEntity(HttpStatus.UNAUTHORIZED).toString();
}
Here is how i login to service in my frontend JavaScript:
performLoggingToService(){
var login = document.getElementById("loginField").value;
var password = document.getElementById("passwordField").value;
var url = "http://localhost:8080/mvc1/login";
var method = "POST";
var crendentialsObject = { "login": login, "password": password };
var crendentialsObjectJSON = JSON.stringify(crendentialsObject);
console.log(crendentialsObjectJSON);
var req = new XMLHttpRequest();
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/json");
req.send(crendentialsObjectJSON);
//console.log("Is this undefined: "+(loginComponent==undefined));
var props = this.props;
var thisObjectPointer = this;
req.onload = function (e,thisObject=thisObjectPointer) {
var status = req.status; // HTTP response status, e.g., 200 for "200 OK"
var data = req.responseText; // Returned data
if(data.includes("200 OK")){
console.log("Checking LOGON STATE METHOD#2: ");
thisObject.props.refreshLogonStateInMainBand(login);
} else {
// inform user about wrong credentials
}
}
}
An then when i perform check if i am already logged in one address /checkLogon I use:
checkLogonState(currentUserName) {
console.log("CheckLogonState CALLED!");
var url = "http://localhost:8080/mvc1/checkLogon";
var method = "GET";
var req = new XMLHttpRequest();
var loginData;
req.overrideMimeType("application/json");
req.open('GET', url, true);
req.onload = function() {
}
req.send();
req.onreadystatechange=(e)=>{
if(req.readyState === 4 && req.responseText.length>0) {
if(req.responseText.includes("200 OK")){
console.log("Authenticated!!!");
this.changeMainComponentStateToLogin();
this.currentUserName = currentUserName;
this.oneTimeLogonCheckAction=false;
} else {
console.log("Not logged in!!!")
this.changeMainComponentStateToIdle();
this.currentUserName=undefined;
this.oneTimeLogonCheckAction=true;
}
this.forceUpdate();
}
}
}
As you may expect responseTest includes 404 Unauthorized not 200 OK.
I tried it on InternetExplorer, Microsoft Edge and Chrome. None of them reuses session.
After each of my requests console on server side shows that the requests are sent from other sessions - each request in a new session.
I would like to get to know how can I use same session if i use one the same browser window through many requests.
Set withCredentials to true for all XMLHttpRequest,
var req = new XMLHttpRequest();
req.withCredentials = true;
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/json");
req.send(crendentialsObjectJSON);
will help to persist the session across calls.
At server side add this to all your controllers to solve cors issues,
#CrossOrigin(origins = ["http://localhost:3000"], allowCredentials = "true")

Porting function from java (Android) to AngularJs

I'm trying to write an old native Android app with Ionic and I need help for the http request. I'm newbie in AngularJS (js too).
My Android code has a function like:
String address = "http://www.example.com";
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(address);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("param", sParam));
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(responsegetEntity().getContent()));
StringBuilder sBuilder = new StringBuilder();
String sLine = "";
while ((sLine = rd.readLine()) != null) {
sBuilder.append(sLine).append("\n");
}
String sContent = sBuilder.toString();
(...parsing sContent...)
} catch (Exception e) {
//something
}
and if there are more then one page I call a function like
String address = "http://www.example.com/result.do?page="+ iPage;
HttpPost post = new HttpPost(address);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("param", sParam));
Cookie ck = client.getCookieStore().getCookies().get(0);
pairs.add(new BasicNameValuePair("param_ck", ck.getValue()));
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
(..parsing..)
}
So, I read the html content of a webpage (I'm not the owner) and I do somethings with that.
I tried $http.post but I'm not sure if it's the same
.factory('Service', function($q,$http) {
return {
getResult: function(param) {
var q = $q.defer();
var address = "http://www.example.com";
var sParam = "param";
$http({
url: address,
method: "POST",
data: {
'param' : sParam
}
})
.then(function(response) {
(...)
q.resolve(position);
},
function(error) {
(...)
q.reject(error);
});
return q.promise;
}
};
});
PS: I get the
No 'Access-Control-Allow-Origin' header is present on the requested resource.
with that.
Can you help me?
I am not entirely sure why you don't get a similar error with your Android code, or even if you were supposed to, as I am not familiar with native Android itself. But the reason that you get this with Angular in Ionic is that the server requires to implement CORS to get rid of that.
From MDN:
A resource makes a cross-origin HTTP request when it requests a resource from a different domain than the one which the first resource itself serves. For example, an HTML page served from http://domain-a.com makes an src request for http://domain-b.com/image.jpg. Many pages on the web today load resources like CSS stylesheets, images and scripts from separate domains.

Redirect to new page as response to XHR post request

I have no way to fix the javascript. The page uses a XHR
function openPOST(url, params, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader('Content-Type', "application/x-www-form-rlencoded");
xmlhttp.send(params);
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4) {
if (xmlhttp.status === 200) {
if (callback) callback(this.responseText);
}
}
}
return xmlhttp;
};
At the time of page load, use the following query
document.addEventListener('DOMContentLoaded', function () {
...
function go() {
openPOST("/home/someaction", "query=123", function (count) {
document.querySelector("h1").textContent = count;
});
}
...
go();
...
});
Is it possible to implement such a code to ASP.NET MVC so he moved on to another page, but did not put the result in another page ?
I need to POST requests are redirected to the page to a different address.
the following code inserts the result in document.querySelector("h1").textContent
public void someaction() {
Response.Status = "307 Temporary Redirect";
Response.AddHeader("Location", "http://example.com");
}
EDIT:
User opened an old version of our webpage in his browser. This webpage makes an ajax call to our webserver and inserts response as a string (no eval(), js code won't work). Is there are any way to reload this web page from our server?
On your action method, you can call a Javascript code by returning a Javascript result
[HttpPost]
public ActionResult someaction() {
if (Request.IsAjaxRequest()) {
return JavaScript("document.location.href=\"http://www.google.com\"");
} else {
return Redirect("http://wwww.google.com");
}
}

How to send data from outside site to my server via AJAX?

I am written the bookmarklet, which takes pictures and videos from a site and must send it to my server via AJAX. The problem is in crossdomain AJAX request - I have got an error:
XMLHttpRequest cannot load http://mysite.com/community/bookmarklet/. Origin http://www.some-nice-site.com is not allowed by Access-Control-Allow-Origin.
How to solve data sending to my server from third-part sites?
Note: I use only plane javascript, this is the stipulation of development.
my code:
function getXmlHttp(){
var xmlhttp;
if (typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
} else {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
};
return xmlhttp;
};
function vote(data) {
var req = getXmlHttp();
req.onready = function() {
if (req.readyState == 4 & req.status == 200) {
alert('OK');
}
}
req.open('GET', 'http://mydomain.com/community/bookmarklet/');
req.send(JSON.stringify(data()));
};
function dataProcessing(){
//some processing
return data;
};
// I tried it, but not deeply understand.
function JSONPresponse(){
document.getElementById('popup_body').innerHTML = 'done!';
};
(function(){
function pasteIt(){
// this function is builds the form, which get data for dispatch to my server.
};
pasteIt();
document.getElementById('my_button').addEventListener('click', function() {vote(dataProcessing)}, false);
}());
It is quite clear... the site you are attempting is prohibiting connection from outside world. You can try by modifying your http headers in request. See:
Access-Control-Allow-Origin Multiple Origin Domains?
Cannot properly set the Accept HTTP header with jQuery
As #jakeclarkson told - JSON-P is the solution, not the only, but useful for me.
XMLHttpRequest is not needed anymore. Instead it vote(data) function creates the script to build URL with params:
function vote(data) {
var script = document.createElement('script'),
data = JSON.stringify(data());
script.type = 'text/javascript';
script.src = 'http://mysite.com/api/bookmarklet/?vids='+encodeURIComponent(data);
document.getElementsByTagName('head')[0].appendChild(script);
};
The script is fulfilled, so URL is called and params already in the server.

Categories