Passing request parameters on an API fetch Request - javascript

How do I pass down parameters to a fetch request? I have this api call to fetch the logged in users username. How do I pass the returned results to the other fetch request route as it's request parameter?
//Gets logged in user's username
async function getProfile(){
try {
const response = await fetch(`${SUMMIT_API}/users/myprofile`,{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${myToken}`
},
})
const data = await response.json();
console.log(data)
return data.profile
} catch (error) {
console.log('Oops Something Went Wrong! Could not get that user profile.');
}
}
Results from above fetch:
//Request parameters is the logged in user's username in the route retrieved from above fetch request
async function userChannel(){
try {
const response = await fetch(`${SUMMIT_API}/users/myprofile/**${username}**/channel`,{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${myToken}`
}
})
const data = await response.json();
console.log(data)
return data.profile;
} catch (error) {
console.log('Oops Something Went Wrong! Could not render userChannel');
}
}
How do I get the information from first request passed to the second?

Since the information you want seems to be supplied by your async function getProfile, it seems like you simply need to await getProfile() and pull the necessary information out:
var profile = await getProfile();
var username = profile[0].username;

Related

How to do Spotify Api Post Request using Axios

I'm trying to add a song to the playback queue using this endpoint:
const add = async () => {
try {
const url = `https://api.spotify.com/v1/me/player/queue?uri=${songUrl}&device_id=${deviceId}`
await axios.patch(url, {
headers: {
Authorization: `Bearer ${to}`
},
})
} catch (error) {
console.log(error);
}
}
I'm getting a status 401 error with a message that says no token provided. But when I console.log the token it shows up.
I haven't worked with the Spotify API yet, however, according to their docs, you need to send a POST request, not a PATCH, which is what you used.
Use axios.post() instead of axios.patch():
const add = async (songUrl, deviceId, token) => {
try {
const url = `https://api.spotify.com/v1/me/player/queue?uri=${songUrl}&device_id=${deviceId}`;
await axios.post(url, {
headers: {
Authorization: `Bearer ${token}`,
},
});
} catch (error) {
console.log(error);
}
};
The second param of your post request should be body and the third param should be headers. Also, you haven't added all the headers as mentioned in the documentation.
headers: {
Accept: 'application/json',
Authorization: 'Bearer ' + newAccessToken,
'Content-Type': 'application/json',
}
Get your access token from here: https://developer.spotify.com/console/post-queue/
If it still doesn't work try the curl method as mentioned in their docs and if it works, switch it to axios.
I had the exact same issue as you, what I realised was I was passing the header as data rather than as config. This code below should work for you as it works for me.
const add = async () => {
try {
const url = `https://api.spotify.com/v1/me/player/queue?uri=${songUrl}&device_id=${deviceId}`
await axios.post(url, null,{
headers: {
Authorization: `Bearer ${to}`
},
})
} catch (error) {
console.log(error);
}
}

Fetch: HTTP GET Showing data not working via web api consuming gRPC

I'm trying see in console some data from a http Get method but it doesn't work, showing me error 400 and Idk how I get is errors... I did with the post method and it works well
I'm also trying to do authentication with bearer tokens but idk if this is correct
This is the fetch get method:
function getUsers() {
fetch(uri_3_2, {
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem("key")}`,
}
//the localStorage.getItem("key") is a key I have when I first to other fetch call,
//so this getUsers() is calling after the first fetch I have
})
.then(response => response.json())
.then(data => _displayItems(data))
.catch(error => console.error('Unable to get Users.', error));
}
function _displayItems(data) {
console.log(data.Email); //undefined
console.log(data.Username); //undefined
console.log(data); //this works but don't show the data, I have so it gives me error...
}
I think this one is correct but I will show anyway
Controller method
[HttpGet("getAllUserInfo_2"), Authorize] //message is empty but it works
public async Task<ActionResult<ListUsersResponse>> GetAll_2(MessageRequest message)
{
var results = await _userClient.GetAllUsersAsync(message);
return Ok(results);
}
gRPC service
public override Task<ListUsersResponse> GetAllUsers(MessageRequest request, ServerCallContext context)
{
ListUsersResponse response = new ListUsersResponse();
var query = from emp in _context.Users_4
select new ListUserResponse()
{
Username = emp.Username,
Email = emp.Email
};
response.LstUsers.AddRange(query.ToArray());
return Task.FromResult(response);
}

Refactor from fetch to await that can yield same result

So I moved over a non-reusable fetch request code snippet to my API:
let response = await fetch(visitURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + userJWT
},
body: JSON.stringify(endingVisit)
});
if (response.ok) {
let {visitId, createdAt} = await response.json();
const viewVisitDto = new ViewVisitDto(`${visitId}${createdAt}${visitorId}${doctorId}${oldPatientId}`);
return viewVisitDto;
} else {
throw new Error("deactivated!")
}
I was able to get this far:
axios.post(visitURL, {
headers,
body: JSON.stringify(visit)
}).then((response) => {
console.log(response);
}).catch((error) => {
console.log(error);
})
But does not exactly give me the visitId and createdAt from the response and I cannot use a response.ok nor a response.json(). Essentially I need to pull out that visitId and createdAt that should be coming back in the response.
I also tried just using node-fetch library, but although in VS code it seems to accept it, TypeScript is not happy with it even when I do install #types/node-fetch and even when I create a type definition file for it, my API just doesn't like it.
Guessing what you are after is
// don't know axios, but if it returns a promise await it
const dto = await axios.post(visitURL, {
headers,
body: JSON.stringify(visit)
}).then((response) => {
// parse response
return {resonse.visitId, resonse.createdAt}
}).then(({visitId, createdAt}) => {
// form dto (where are other vals)?
return new ViewVisitDto(`${visitId}${createdAt}${visitorId}${doctorId}${oldPatientId}`);
}).catch((error) => {
console.log(error);
})
However - you don't mention where doctorId and oldPatientId come from... You try providing more info, including output of the console.log's and the surrounding code

How to convert axios to fetch?

I'm familiar with posting data with Axios, but trying to use fetch instead. How would I convert to a fetch request, I think what I'm doing is correct...
const data = new FormData();
The following axios request works:
data.append( 'Image', this.state.image, this.state.image.name );
axios.post( '/api/upload', data, {
headers: {
'accept': 'application/json',
'Accept-Language': 'en-US,en;q=0.8',
'Content-Type': 'multipart/form-data;',
}
})
.then ...
I tried to convert here;
data.append( 'Image', this.state.image, this.state.image.name );
fetch( '/api/upload', data, {
method: 'POST',
headers: {
'accept': 'application/json',
'Accept-Language': 'en-US,en;q=0.8',
'Content-Type': 'multipart/form-data;',
},
body: JSON.stringify(data)
})
.then ...
Returns 404 error, not found.
What am I failing to do here?
2021 answer: just in case you land here looking for how to make GET and POST Fetch api requests using async/await or promises as compared to axios.
I'm using jsonplaceholder fake API to demonstrate:
Fetch api GET request using async/await:
const asyncGetCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
});
const data = await response.json();
// enter you logic when the fetch is successful
//example: show success modal, clear form, route to another page etc.
console.log(data);
} catch(error) {
// enter your logic for when there is an error,
// example: open a modal with error message.
console.log(error)
}
}
asyncGetCall()
Fetch api POST request using async/await:
const asyncPostCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
});
const data = await response.json();
// enter you logic when the fetch is successful
//example: show success modal, clear form, route to another page etc.
console.log(data);
} catch(error) {
// enter your logic for when there is an error,
// example: open a modal with error message.
console.log(error)
}
}
asyncPostCall()
GET request using Promises:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then(res => res.json())
.then(data => {
// enter you logic when the fetch is successful
//example: show success modal, clear form, route to another page etc.
console.log(data)
})
.catch(error => {
// enter your logic for when there is an error,
// example: open a modal with error message.
console.log(error)
})
POST request using Promises:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
})
.then(res => res.json())
.then(data => {
// enter you logic when the fetch is successful
//example: show success modal, clear form, route to another page etc.
console.log(data)
})
.catch(error => {
// enter your logic for when there is an error,
// example: open a modal with error message.
console.log(error)
})
GET request using Axios:
const axiosGetCall = async () => {
try {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts')
// enter you logic when the fetch is successful
// example: show success modal, clear form, route to another page etc.
console.log(`data: `, data)
} catch (error) {
// enter your logic for when there is an error,
// example: open a modal with error message.
console.log(`error: `, error)
}
}
axiosGetCall()
POST request using Axios:
const axiosPostCall = async () => {
try {
const { data } = await axios.post('https://jsonplaceholder.typicode.com/posts', {
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
// enter you logic when the fetch is successful
// example: show success modal, clear form, route to another page etc.
console.log(`data: `, data)
} catch (error) {
// enter your logic for when there is an error,
// example: open a modal with error message.
console.log(`error: `, error)
}
}
axiosPostCall()
fetch only takes two arguments.
fetch('/api/upload', {
method: 'post',
body: JSON.stringify(data),
headers: {
'accept': 'application/json',
'Accept-Language': 'en-US,en;q=0.8',
'Content-Type': 'multipart/form-data;',
},
})
.then(res => res.json())
.then(json => console.log(json));

Handle asmx C# Exception with fetch API

First of all sorry for my English...
I have an asmx in C# that send data in json with an fetch API Call in the client side, i was using the jQuery.Ajax call before, but i want to start using fetch API.
This is how i do the Fetch Call.
I call the function fetchcall passing the url and if is needed the JS object with the parameters to be send by POST
const jdata = await fetchcall(url, "")
Then in my function i do this
async function fetchcall(url, data) {
const PostData = {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
dataType: 'json'
//credentials: 'include'
}
if (data) { PostData.body = JSON.stringify(data) }
try {
const response = await fetch(url, PostData)
const json = await (handleErrors(response)).json();
//This is a temporary solution to the problem
if (json == 'Su sesion ha expirado favor de ir a pagina de login e iniciar session') {
alert(json);
return false;
}
return json
} catch (e) {
console.log(e)
}}
And this is the handleErrors function
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
Right now i am testing the error without sending the credentials, so i get a error for the Session
And in my C# asmx i have this
[WebMethod(Description = "Load Countries", EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string fillcbocountries()
{
var authCookie = Session["uid"];
if (authCookie == null)
throw new Exception("Your session has expired please go to login page and start session");}
With that the web services is throwing me an error with the message of Your session has expired please go to login page and start session
But wen i check the response of the fetch API in the handleError function i only get a statusText:"Internal Server Error" and i want the message that the server respond.
With jQuery.Ajax i do this
error: function (xhr, textStatus, error) {
var errorM = $.parseJSON(xhr.responseText);
console.log(errorM.Message)
}
And i get the
Your session has expired please go to login page and start session
Thank you for the help and regards
I discovered how to handle the error correctly if an exception is sent from C#
I removed the handleErrors function and check the response inside the fetchcall
so if the response.ok is false then i check the json data that the server respond and get the json.Message.
This is the end code
async function fetchcall(url, data) {
const PostData = {
method: 'POST',
headers: {
"Accept": "application/json",
'Content-Type': 'application/json; charset=utf-8'
},
dataType: 'json',
credentials: 'include'
}
if (data) { PostData.body = JSON.stringify(data) }
try {
//const url = 'services/common.asmx/fillcbopais'
const response = await fetch(url, PostData)
const jdata = await response.json();
if (!response.ok) {
alert(jdata.Message);
throw Error(jdata.Message)
}
return json
} catch (e) {
console.log(e)
}}
In case someone else has this problem I hope I can help

Categories