Get Token From Api Dynamically To Access Content - javascript

I need to have the token to access the content like the announcement in my code. But what i do is to copy the token generated from loginUser() and paste it inside the getAnnouncement() under the fetch. I wrote Authorization : 'Bearer esuigiugeguigiguigi' <--- this is the token. The problem with this is that i need to copy and paste again the token every time it expires.
function loginUser(){
fetch('http://sample_website.com/api/auth/login', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: document.getElementById("email").value,
password: document.getElementById("password").value
})
})
.then(data => data.json() )
.then(data => {
if(data.response){
redirect: window.location.replace("../Sample/Home.html")
} else{
alert("Invalid Email or Password");
}
})
.catch((err) => {
console.error(err);
})
}
function getAnnouncement(){
fetch('http://sample_website.com/api/announcements', {
method: 'GET',
headers: {'Content-Type': 'application/json',
Authorization : 'Bearer esuigiugeguigiguigi'},
})
.then(data => data.json())
.then(data => { console.log(data)
const output = document.getElementById("display");
output.innerHTML = `<ul>
<li><h2>${data.data.data[0].title}</h2></li>
<li>${data.data.data[0].body}</li>
<li>Created: ${data.data.data[0].created_at}</li>
</ul>`;
})
.catch((err) => {
console.error(err);
})
}

Usually the response from an API call to get the token will hold:
the token
the duration of the toke
a link to refresh the token
One basic way of dealing with this is to keep the token data in localStorage or in memory or something (you can decide for yourself), and then just use it on any request that needs authorization.
It is possible that the API in question gives a specific error in case a token has expired. You can then catch it, use the link to refresh the token to get a new one, and repeat the request.
As there is not much info about the API in hand, or what you're doing and what (if any) framework you are using, this it the best answer I can provide at the moment. There are a lot of libraries out there handling this stuff already, so you might want to look into existing solutions as well.

Related

Localhost Fetch request failing

I have a flask api (running on host='0.0.0.0', port=8080, which should cause it to run on my priv ip), and a javascript fetch request, which when called isnt able to reach the api for some reason. The javascript is running in a webpage hosted on http://127.0.0.1:5500. Yes I have tried curl and it works perfectly. The code for the fetch request is
const lbutton = document.getElementById("lbutton");
lbutton.addEventListener("click", function() {
console.log('button clicked');
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
fetch('http://not gonna give out my ip:8080/api/log', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({email: email, password: password})
})
.then(response => {
console.log('Success:', response);
if (response.ok) {
console.log('worked');
} else {
throw new Error('Server response was not OK');
}
})
.catch(error => {
console.error('Error:', error);
});
});
Can someone explain to me why it is not working, I have been trying to figure out how to do this for ages.
I tried to make it send a POST request to my api, which should work and the api should receive login info, but the request is not making it through at all.
The fetch api is making a GET request to http://127.0.0.1:5500/login.html?email=test#gmail.com&password=test

How can I update the message body using gmail API in javascript

I have got the message body. Now I want to update it according to my needs. I am using this login/code. but it says 400 error. I think issue is in body parameter of the request. Would you please help me there?
var token = localStorage.getItem("accessToken");
var messageId = "18514426e2b99017";
async function updateMessageBody() {
var updatedBody = "Hello,\n\nThis is the UPDATED message body.\n\nBest regards,\nJohn";
const API_KEY = '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-CXIk';
const headers = {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
};
const response = await fetch(`https://gmail.googleapis.com/gmail/v1/users/me/messages/18514426e2b99017/modify?key=['API_KEY']`, {
method: 'POST',
headers: headers,
body: JSON.stringify({
raw: window.btoa(unescape(encodeURIComponent(updatedBody)))
})
});
if (!response.ok) {
// throw new Error(`Request failed with status code ${response.status}`);
}
return await response.json();
}
updateMessageBody()
.then(response => {
console.log('Message body updated successfully:', response);
})
.catch(error => {
});
Checking the documentation, it states that a message body can't be altered once it has been created, meaning that once you have already created an email this message can't be changed. You can verify this here.
You can instead update a message draft which is possibly what you are trying to do, however using the endpoint you have in your code this won't be possible and will lead to the error message you are getting, try using instead the users.draft.update method that allows you to modify the content of the draft sitting in your mailbox. Please note as well that using the method users.messages does not have any update method as they only have the modify one's, those methods can only update the labels though so please be aware of that.

Getting 401 error when using redmine API for a POST request even though I have included the api key

I am trying to make a post request to create a new wiki page using the redmine-api. I am using JavaScript and Axios. However I a getting a 401 error(UnAuthorize).
My goal is to be able to send a word document to my redmine and create a wiki page.
I am using the Api key provided and I did enable the rest api feature in my redmine setting
I have included the api key in the header however it is not working.
var wordDocument = "./Redmine.docx"
axios.post('<website url>/uploads.json', {
headers: {
'Content-Type': 'application/octet-stream',
'Cache-Control': 'no-store',
'key': '<api-key>'
},
data:wordDocument
})
.then(function (response) {
console.log("succeeed---> ");
console.log (response)
})
.catch(function (error) {
console.log("failed-----> ");
console.log(error.response.headers)
console.log(error.message)
console.log("failed-----> ");
})
I am getting a status: '401 Unauthorized',
Try using the other authentication methods mentioned in the docs:
x passed in as a "key" parameter
- passed in as a username with a random password via HTTP Basic authentication
- passed in as a "X-Redmine-API-Key" HTTP header (added in Redmine 1.1.0)
https://www.redmine.org/projects/redmine/wiki/Rest_api#Authentication
Also ensure that you're using the correct API key.
You can find your API key on your account page ( /my/account ) when logged in, on the right-hand pane of the default layout.
Alright I got it working.
I did "axios({})" instead of "axios.post". I do not know what the different is? I thought it was the same.
Here is my code for anyone who run into this.\
var wordDocument = "./Redmine.docx"
axios({
method: 'post',
url: '<redmind_url>/uploads.json',
headers: { 'Content-Type': 'application/octet-stream'},
params: { 'key': '<api key>'},
data: wordDocument
})
.then(function (response) {
console.log("succeeed---> ");
console.log(response.data)
})
.catch(function (error) {
console.log("failed-----> ");
console.log(error.response.statusText, "-->", error.response.status);
console.log(error.response.headers)
console.log(error.message)
console.log("failed-----> ");
})

JavaScript - Cannot GET /api/list

I am working on a website where a user should be able to post items to a list. Right now, when I try posting something it comes up with an error saying
Failed to load resource: the server responded with a status of 422 (Unprocessable Entity).
When clicking on it in the console it opens a new tap where it just says
Cannot GET /api/list
Also in the command prompt, it says
Unhandled rejection Error: Can't set headers after they are sent.
Does anybody know why this might be and what I can do to fix it? Here are some snippets of my code:
Index.HTML:
fetch('/api/list', options)
.then(response => response.json())
.then(response => {
if (response.status == 'OK') {
console.log('song is added')
getList(items)
} else {
alert(response.message)
}
})
}
Server.js:
app.post('/api/list', userIsAuthenticated, (req, res) => {
let {
titleArtist
} = req.body
let user_id = req.session.user.id
// seaching for user id in database
let query = {
where: {
userId: user_id
}
}
It might also be somewhere else in the code it goes wrong. Let me know if I should post more snippets of code.
This is because you are making a GET request to POST API.
This is how you can make POST request
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

Fetch POST Unexpected end of input Erorr

I'm trying to do a POST request for authentication in Redux and I'm passing email & password as the body but it returns this error in the console:
Uncaught (in promise) SyntaxError: Unexpected end of input
I looked around for the answer and many people suggested that it might be a missing } brace but I looked for it and I don't think it's that.
Here is my fetch function.
export function loginUser(creds) {
let config = {
mode: 'no-cors',
method: 'POST',
headers: { 'Content-Type':'application/x-www-form-urlencoded' },
body: `email=${creds.email}&password=${creds.password}`
};
return dispatch => {
dispatch(requestLogin(creds));
return fetch('http://localhost:4000/api/authenticate', config)
.then(response =>
response.json()
.then(user => ({ user, response }))
).then(({ user, response }) => {
if (!response.ok) {
dispatch(loginError(user.message));
return Promise.reject(user);
} else {
localStorage.setItem('id_token', user.token);
dispatch(receiveLogin(user));
}
});
};
}
The fetch POST method calls the API and I see it in the networking tab and I see the response too but the fetch request stops at .then(response => after the url and config.
It's been two days and still can't find the solution. By the way, this works fine in Postman(chrome extension), so nothing wrong with the API.
Thanks
Answer EDIT: The issue was related to CORS, so for anyone having the same issue as I did.
I solve the same question when I remove
mode: 'no-cors'
from the config.
Anyway you could simplify your snippet code to:
fetch('http://localhost:4000/api/authenticate', config)
.then(response => response.json())
.then(({ user, response }) => {
And you should might add catch method to handle an Error object.

Categories

Resources