Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

291
Visualizações
How to store JWT from Post-Response and send it in HTML-forms?

I want to send a JWT with the uploaddata when the user has logged in. To get it, I first need to use the LogIn Form. When I click on the loginButton, the function login() is called to make the post request with the formdata and waits for the response to retrieve the JWT, but an error indicating CORS-Header is missing is shown in the console at login-function "const json = await data.json();". However, i am able to see the token in the developer console.

Then when using the upload form, the JWT needs to be send as the authorauation header with the uploaded images as body. I want to accomplish this with plain javascript. This is what I have so far:

<form id="loginform">
    <input type="text" id="username" name="username" placeholder="Username">
    <input type="password" id="password" name="password" placeholder="Password">
    <input id="loginButton" type="submit">
</form>
    
<form id="uploadform" enctype="multipart/form-data">
    <input type="file" id="images" name="images" multiple data-max="5" accept="image/jpg, image/jpeg, image/png" >
    <input id="sendImagesButton" type="submit">
</form>

<script type="text/javascript">
    
    const loginform = document.getElementById("loginform");
    loginform.addEventListener('submit', login);
    async function login(event){
        event.preventDefault();
        const data = await fetch("http://localhost:8000/api/login", {
            method: "POST",
            body: new FormData(this)
        });
        const json = await data.json();
        alert("test jwt retrieved");
        localStorage.setItem("token", json.access_token);
    }
    const pdfform = document.getElementById("uploadform");
    pdfform.addEventListener('submit', convert_to_pdf);
    function convert_to_pdf(event){
        event.preventDefault();
        const res = await fetch("http://localhost:8000/api/convert_to_pdf", {
            method: "POST",
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': ' Bearer ' + localStorage.getItem("token")
            },
            body: new FormData(this)
        });
    }
</script>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

From what i can see(not that much) i can say that the process of the authentication with JWT should be:

  • Send a POST request with the data you want in the token payload
  • In the server create the token
  • Send back the token(should be a single string, check it)

Now that you have access to the token on the client-side you can save it in the local or session storage(localStorage or sessionStorage).

Another option would be send the token on every request through cookies. It really depends on you.

EDIT: once you get the token back from the login request and you save it in the storage you have it available from anywhere in the client code, however the only way of sending it to the server via the update form(except using an hidden input) would be, in the script:

document.querySelector('#uploadform').addEventListener('submit', e => {
 // here you can access and manage your form value and also of course access the token value
 // to send it to client you can use something like axios so you would do
 e.preventDefault(); // that prevent the form to send its request
 // now send you request manually with your data for e.g.
 axios.post('http://localhost:8000/api/convert_to_pdf', /* your data here */)
})
about 4 years ago · Juan Pablo Isaza Relatório

0

Default browser action for form submit by POST is to render response content. If it is not desired behavior you'll have to perform request from JS manually e.g. by using onsubmit attribute.

I found tutorial about that on Mozilla developer site.

Also you'll have to store JWT somewhere, maybe local-storage, when read it back and add it to Authorization header in next request, also done through JS and not standard browser submit.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda