How to save a request body? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 days ago.
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()

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”);

Related

How to redirect after a POST method using Fetch? [duplicate]

This question already has an answer here:
Data is undefined in fetch post request
(1 answer)
Closed 2 months ago.
I posted form data to an API endpoint and I want to redirect the browser to the response text. I seem to not be able to figure out what I am missing.
Below is what I have been able to do so far:
const formEl = document.querySelector("form");
formEl.addEventListener("submit", (event) => {
event.preventDefault();
const formData = new FormData(formEl);
const data = new URLSearchParams(formData);
fetch("https://example.com/users", {
method: "POST",
body: data
})
.then(async response => console.log(await response.text()))
.then(window.location.href = (response.text()))
});
Hope this will help you.
fetch("https://example.com/users", {
method: "POST",
body: data
})
.then(async response => response.text())
.then(result => {
window.location.href = result
});

Why non async function is running asynchronously? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 months ago.
I have a function that must validate some artist from Spotify API, but when I run it artists[] remains empty because the function is running asynchronously, it fills the variable user without having set artists.
let artists = []
function setArtists(input) {
artists.length = 0
let parsedInput = input.value.split(",")
parsedInput.forEach(artist => {
validateArtist(artist)
})
}
function validateArtist(s) {
let token = localStorage.getItem("Token")
let url = "https://api.spotify.com/v1/search?type=artist&q=" + s
console.log(url)
fetch(url, {
"method": "GET",
"headers": {
'Accept': 'application/json',
'Content-Type': 'application/json',
"Authorization": "Bearer " + token,
}
})
.then(response => {
if (response.status === 401) {
refreshToken(s)
}
return response.json()
})
.then(searchedResults => searchedResults.artists.items.length != 0)
.then(isArtist => {
if (isArtist) {
artists.push(s)
}
})
}
Here is were I call the function, I call it before so it can fill artists
setArtists(document.getElementById("artistiPreferiti"))
var user = {
username: document.getElementById("username").value,
email: document.getElementById("email").value,
password: document.getElementById("password").value,
gustiMusicali: document.getElementById("gustiMusicali").value,
artistiPreferiti: artists
}
What am I missing?
The async (and await) keywords are tools to manage promises which are, in turn, tools to manage asynchronous code in a standard way.
The use of the async keyword doesn't make a function run asynchronously and not using the keyword doesn't prevent asynchronous code from being so.
fetch runs asynchronously. Your code uses fetch. Therefore your code is asynchronous.

How to get fetch response and then anssing the response to var in Javascript? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I am trying to do a GET request with vanilla javascript from a .html, and I am looking to assign the response inside a variable, I have to use the response to manipulate the DOM however, I get a Promise < pending > and not a JSON
This is my code:
let data = fetch('http://localhost/api/products')
.then(response => response.json())
console.log(data)
I'd like to get this from console.log(data):
{ "name": "SHOES", "price": 129}
this code will be a good guide, you can get json data at then second then
const getCart = () => {
fetch("/cart.js", {
method: 'GET',
headers: new Headers({'content-type': 'application/json', 'X-Requested-With':'xmlhttprequest'})
}).then(res => {
return res.json();
}).then(json => {
console.log(json);
});
}

Fetch data from api with graphql [duplicate]

This question already has answers here:
How to call GraphQL API from Node.js/Express server?
(2 answers)
Closed 2 years ago.
I am trying to connect to a website and they have given me :
Url: https://api.demo...
headers:"x-api-key" and "x-api-user"
I do not know how to make the connection with them,I tried the code below:
const query = `
query {
some query here
}
`;
const url = ``
const opts = {
method: "POST",
headers: { "x-api-key": ,
"x-api-user": , },
body: JSON.stringify({ query })
};
Is this the right way? when I run it npm start=> App Crashes I am new to javascript and I dont even know how to make the search in google,can someone please guide me to a tutorial,link or please respond with the right way?
Thank you for your understanding
You can do it using the fetch call.
const query = `query {
Some query
}`;
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query
})
})
.then(r => r.json())
.then(data => console.log('data returned:', data));

GraphQL returns null on mutation [duplicate]

This question already has answers here:
Why does a GraphQL query return null?
(6 answers)
Closed 3 years ago.
I'm using GraphQL to connect to multiple RESTful endpoints. I'm writing a mutation to update user details, however GraphiQL is showing the following response of null rather than the updated user ID and name...
{
"data": {
"updateUser": null
}
}
updateUser: (parent, args) => {
const { id, name } = args;
return fetch(`${url}/users/${id}`, {
method: 'PUT',
body: JSON.stringify({ id, name }),
headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => console.log(json));
},
Thanks in advance.
You need to return your resolved json, otherwhise there is no returning value for the fetch call.
.then(json => json);
or if you want
.then(json => {
console.log(json);
return json;
});

Categories