Alert message Response Headers

Asked

Viewed 430 times

4

I’m on a project. NET, in which I create a login page and check the DLL, and in this check, is passed a string of a message that I need to capture with a Typescript to give the alert. This message is already being sent, and it appears there in the page header, as soon as a post is made.

What I need now is to take this message to make a simple alert() and it can appear to the user.

Here is a print that shows how the message is in the header:

inserir a descrição da imagem aqui

I just need to pick her up and do the Alert.

Help me please Thank you.

I’ve tried this code:

var req = new XMLHttpRequest();
    req.open('GET', document.location.href, false);
    req.send(null);
    var headers = req.getAllResponseHeaders().toLowerCase();
    alert(headers);

of this question https://stackoverflow.com/questions/220231/accessing-the-web-pages-http-headers-in-javascript

but I do not see the message, only this data: inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

I NOTICED SOMETHING ON THE NETWORK

when I post and it returns Alert, the network looks like this: inserir a descrição da imagem aqui

Note that there is only 1 localhost file

and when I click on the Ubmit button, another localhost file appears that does not contain the header "message":

inserir a descrição da imagem aqui

is created by the code req.send(null);

Observe:

inserir a descrição da imagem aqui

The first localhost contains the message, the last one is generated by req.send(null);

In my TS code la no sources, the following error appears on the line:

req.open("HEAD", window.location.href, false);

Synchronous Xmlhttprequest on the main thread is deprecated because of its detrimental effects to the end user’s Experience. For more help, check in https://xhr.spec.whatwg.org/.

EDIT:

In my file . Cs, where I add the header, has the following code:

public async Task OnPostAsync(PARAMETROS){
      CancellationTokenSource backGroundTask = new CancellationTokenSource();
      MobAtivacaoAcesso MobAtivacaoAcesso = new MobAtivacaoAcesso("X", "Z");

      await MobAtivacaoAcesso.AtivacaoVerificarAsync(PARAMETROS); 

      if (!String.IsNullOrEmpty(MobAtivacaoAcesso.MensagemTemporaria)){
          Response.Headers.Add("mensagem", MobAtivacaoAcesso.MensagemTemporaria);
      }

      return;
}
  • The request is asynchronous and you are not waiting for an answer to execute the alert. You need a function callback to be executed when the request is completed... A MDN is a good source and see also the property documentation XMLHttpRequest.onreadystatechange

  • Caro @fernandosavio is not asynchronous, the third parameter is false no . open, indicates synchronous, so it is not used neither onload nor onreadystatechange, I recommend you read: https://answall.com/a/116177/3635

  • This looks like a problem in your back-end, probably you wrote the header only in GET, when you receive the POST does not contain the HEADER

  • actually, I put the Response.header.add() just me a public async Task Onpostasync

  • I tried to put the same way for an Ongetasync, but it continued the same way... @Guilhermenascimento

  • It seems to me that for some reason the command req.send(null); is creating a new localhost file and is picking up the headers of this new page, which does not have the message.... I’ll add a print to the question to make it easier for you to see.

  • 1

    Guys, I’m sorry about the comments. it turned out to be useless because I didn’t realize the call was synchronous. Thank you @Guilhermenascimento for the clarification and I apologize again for the lack of attention.

Show 2 more comments

2 answers

0

Why the alert is showing a different header from the answer I can’t tell you, but the way you’re doing it won’t work anyway, because JS doesn’t expect the response of your request to continue running the next line of code, when you do the alert, the server response has not yet arrived.

To run a line of code only after the answer arrives, you need to place these lines within a function, and then pass this function to the property onload of the request. When the answer arrives, this function will be invoked automatically.

var req = new XMLHttpRequest();
    req.open('GET', document.location.href, false);
    req.onload = function() {
        var headers = req.getAllResponseHeaders().toLowerCase();
        alert(headers);
    }
    req.send(null);
  • but the Alert is working and showing the headers... just does not appear the "message", which is what I would need to pass to the user. Your way also worked, but brought me the same information the way I was doing... ie, my problem has not been solved yet....

  • As far as I can see, you can’t tell what your mistake is just from what was posted. Maybe you have some other request in your code with the same name. Maybe your header isn’t being exposed because of the cross-origin policy, and you need to set up a header on your server called Access-Control-Expose-Headers to allow the browser to read the header message.

  • I believe that req.onreadystatechange is the right property, but the idea is this...

  • @fernandosavio and user140828 only if it is asynchronous will use onreadystatechange or onload (both work), the author’s code is synchronous, so does not use onreadystatechange, of course Xmlhttprequest synchronous is currently aimed at Web Workers, for the main process it is obsolete, and one should then always use asynchronous in this case. But in general the code is correct. A reading of the reply: https://answall.com/a/116177/3635

  • I need this Alert to appear soon after a POST, in which will be checked if the user exists in the database. and Alert will serve to return the message to him (whether access has been allowed or not, whether it is blocked, etc...).

  • @user140828 of a look at the update of my question, maybe you have idea now what it might be

  • @Guillhermenascimento

  • @fernandosavio,

Show 3 more comments

0


First, "message" is not a "valid" header, I really don’t know why this wanting to do this way, headers are usually browser instructions, content BODY should be the place to use something like this, like a reply JSON, I don’t see why you want to reinvent the wheel.

Now let’s get to the problem, in a simple test, with a code like this:

var request = new XMLHttpRequest;

request.open('GET', 'teste.php', false);

request.send(null);
console.log(request.getAllResponseHeaders());

I was returned to console.log:

date: Thu, 23 May 2019 15:33:52 GMT
guilherme: brcontainer
server: Apache/2.4.3 (Win64)
content-type: text/html; charset=UTF-8
mensagem: teste
connection: Keep-Alive
keep-alive: timeout=5, max=99
content-length: 1

That is was returned the headers correctly, with alert also returned perfectly:

exemplo de alert com resultado do XMLHttpRequest.getAllResponseHeaders

A probable explanation:

This using different domains

If you are using different domains, ie Ajax is on one page and the link requested in another, would have to set the Access-Control-Expose-Headers with mensagem to expose the custom header.

Using some add-on/extension

Using some add-on/extension that somehow overrides the HTTP transport, only returning what is of interest (this is just my speculation)

Your browser is outdated

As amazing as it sounds, the test I took was on Chrome 74.0.3729.169 and worked perfectly


To try to solve

If you’ve already updated Chrome to the latest version then create a page without jQuery (I can’t say if jQuery overwrites something, but nowadays I don’t doubt anything like that), an empty HTML with only its basic code and open in an anonymous tab (ensure that no add-on runs in private), so:

<html>
<body>
<script>
var request = new XMLHttpRequest;

request.open('GET', window.location.href, false);

request.send(null);
alert(request.getAllResponseHeaders());
</script>
</body>
</html>

How to get an answer without using headers

As I said at the beginning of the answer, why reinvent the wheel, unlisted headers usually use the prefix x-, which indicates experimental or "non-standard", is your case, that header your mensagem was invented by you, of course it works in the tests done, but not really why transform a bike on a "bike", first, outside the Web Workers do not use XMLHttpRequet synchronous, asynchronous use, has nothing to do with the solution, but rather because outside of Web Workers this is obsolete, still works, but is considered as such. So instead of picking up all headers try to pick up only the one of interest with request.getResponseHeader("mensagem")

Example:

function resposta(url, callback)
{
    var request = new XMLHttpRequest;

    request.open('GET', url, true);//Terceiro parametro TRUE

    request.onreadystatechange = function () {
        //Se ainda não estiver concluido (diferente de 4) ele interrompe o script, irá tentar sozinho novamente em seguida
        if (request.readyState !== 4) return;

        callback(request.getResponseHeader("mensagem"));
    };

    request.send(null);
}

And to wear something like that:

resposta(window.location.href, function (resposta) {
    alert(resposta);
});

Now really if it is a data that comes from the bank really do not see why to do this, it is better to create a URL/ route just for that, with a response in TXT or JSON, something like:

    var request = new XMLHttpRequest;

    request.open('GET', 'status.aspx', true);//Pode ser uma rota se for asp.net-mvc

    request.onreadystatechange = function () {
          //Se ainda não estiver concluido (diferente de 4) ele interrompe o script, irá tentar sozinho novamente em seguida
          if (request.readyState !== 4) return;

          callback(request.responseText); //responseText retorna o BODY da resposta HTTP
    };

    request.send(null);

In your status.aspx put the result of what would be the message directly in the body, something like:

<% Response.Write("sua mensagem aqui"); %>

Route error (on server side)

Probably your error is in the routes, the page that this, the page before of the call XMLHttpRequest is in POST and when calls with XMLHttpRequest is using GET, so probably some configuration your this made the header only sent when POST.

  • Good answer, William, has clarified many of my doubts and you have given me several alternatives to do so. I will do some tests to see if it worked and I give a feedback here... But just to clarify more about the project, it is a project . net core Razor and what I am doing is the following, in the file . Cs of my index, I do, within the onPostAsync method, a check of another method, which is not in this same file, to check whether the user is valid or not, if it allows access and such, and this method returns me a string, which is the message I pass in the header

  • @Samuelmachado it would be nice to put part of this code, both of GET and POST, of . net core, in the question

  • And I pass it as follows: Response.Headers.Add("message", Mobativacaoacesso.Messaging); And this adds it in the Response Header... (was at the request of the company to be passed through there). Now what I need to do is just show the message, for now in a simple Alert() to the user, and I see no better way than using Typescript

  • could not write everything in one message, sorry, if you prefer, I put in the question yes

  • @Samuelmachado yes, you can edit the question as many times as you think necessary and put those details there

  • I did the test of your answer Function, and only returns me null, I believe because of the send and that is not entering the if

  • Guilherme, I left the code I use to add, in the question

  • @Samurai found by your code Response.Headers.Add("mensagem", MobAtivacaoAcesso.MensagemTemporaria); this in the POST, soon the request AJAX is GET, would not even have sense it work ... but I just came across, Voce wants to get the HEADER of the current execution, this is probably because you do not understand well aidna HTTP, it does not work as the way you believe, web is http (there are others, but on site that’s it), so when using Ajax the request is different from the first, are two different things occurring, the solution that would work would be to do something in JSON as I said before [...]

  • [...] or else instead of using HEADER you "print" the message with Razor inside any element, it can be an "embedded JS" in HTML. Can you understand? Do not need to use Headers in your case, it seems to me, just in the own page requested by the POST you create an element with Razor and there put the content, something like: <script>var mensagem = '@(valor que deseja passar do C#/Models/etc para o JS)';</script>, ready you will have a global variable with the message in Javascript @Samuelmachado

  • Okay, I’m still new at this, but you know how I could use this embedded JS by picking up this variable string in which the message is returned?

  • @Samuelmachado the example I passed above did not work?

  • @Samuelmachado I believe that it would only be to pass MobAtivacaoAcesso.MensagemTemporaria in "view" (cshtml think it’s in CORE) using Razor

  • William, sorry for the delay... From what I understand, so it would be <script>var mensagem = '@(MobAtivacaoAcesso.MensagemTemporaria)';</script>, right?

  • @Samuelmachado depends on how this your Model, if this is a model.

  • William, I’ve moved on to the chat room, if you could take a look

Show 10 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.