-2

I'm learning JS, but i can't find how to save a request body after my fetch POST. Using only JS

async function connectUser () {
    const log = document.querySelector("#formulaireConnexion")
    log.addEventListener("submit", function(event){
        event.preventDefault()

        const user = {
            email: event.target.querySelector("[name=mail]").value,
            password: event.target.querySelector("[name=mdp]").value
        }

        const objectUser = JSON.stringify(user)


        fetch("http://localhost:5678/api/users/login", {
            method: "POST",
            headers: {"Content-Type" : "application/json"},
            body: objectUser
        }).then(r => r.json())
        .then(body => console.log(body))
    })
}

connectUser()
  • Where and why do you want to save the request body? On the server or on the local machine? Do you mean the response body? – jabaa Feb 20 '23 at 09:18
  • 1
    Are you just trying to use `body`? See [How do I return the response from an asynchronous call?](/q/14220321/4642212). – Sebastian Simon Feb 20 '23 at 09:19
  • I need to save the body request as var on the local machine. i need it to know if user exist or not, then log with the request body token – SirRichard Feb 20 '23 at 09:29
  • The last comment doesn't make sense. What does it mean to _"save the body request as var on the local machine"_? Are you sure you don't mean the response body? You have the request body in `objectUser`. – jabaa Feb 20 '23 at 09:32
  • Sorry, the request of my fetch is an "ID user" + "token". i get them with my "console.log(body)" but i dont know how to get them in a const outside the function Sorry, didn't write English for a long time.. – SirRichard Feb 20 '23 at 09:35
  • 1
    You can't store the response in a const outside the function. The const is created before the function is evaluated. You can store it in a variable, but you'll have to pay attention to the timing. Read the duplicate. – jabaa Feb 20 '23 at 09:38

1 Answers1

-2

You can save it in session or localstoreAge. Like that const objectUser = sessionStorage.setItem(”saveit”,JSON.stringify(user));

You can then use it like

SessionStorage.getItem(”saveit”);

Atilla
  • 25
  • 5