How to retrieve token from script - javascript

I have the following script:
let url = window.location.href;
const token = {
authorization(url){
authentication_code = url.split("?")[1].split("&")[1].split("=")[1];
this.postData("https://www.strava.com/oauth/token?grant_type=authorization_code&client_id=3035dd7&client_secret=3db4fddd039117f8029b406fe72669a4472594bfb6b&code=" + authentication_code)
.then(data => data.access_token) // JSON-string from `response.json()` call
.catch(error => console.error(error));
},
postData(url = "") {
return fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
})
.then(response => response.json()); // parses response to JSON
}
};
This script should authorize a client to strava and retrieve a token for further usage. Somehow I'm not able to understand how to get the token out of the const token.
when I call token.authorization(). It will authorize. But I have no idea how to retrieve the data.access_token from the function.
Thanks.

A simple return statement could be used before this.postData and you would send the token in the promise.
let url = window.location.href;
const token = {
authorization(url){
authentication_code = url.split("?")[1].split("&")[1].split("=")[1];
return this.postData("https://www.strava.com/oauth/token?grant_type=authorization_code&client_id=3035dd7&client_secret=3db4fddd039117f8029b406fe72669a4472594bfb6b&code=" + authentication_code)
.then(data => data.access_token) // JSON-string from `response.json()` call
.catch(error => console.error(error));
},
postData(url = "") {
return fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
})
.then(response => response.json()); // parses response to JSON
}
};
and when calling, you get a promise in return with the token, so
token.authorization(url).then(tokenFromResponse=>console.log(tokenFromResponse));
Now you can use the token as desired.

Related

node Js + JS input = document.getElementById

there is a node JS script (app.js) that sends a letter to the mail:
const { response } = require("express");
const express = require("express");
const nodemailer = require("nodemailer");
const app = express();
const port = 5000;
//
function sendEmail(tel) {
return new Promise((resolve, reject) => {
var tranporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: ,
pass: ,
},
});
const mail_configs = {
from: "myEmail",
to: "artemdvd#mail.ru",
subject: "Testing Koding 101 Email",
text: "tel",
};
tranporter.sendMail(mail_configs, function (error, info) {
if (error) {
console.log(error);
return reject({ message: "An error has occured" });
}
return resolve({ message: "Email sent succesfuly" });
});
});
}
app.get("/", (req, res) => {
sendEmail()
.then((response) => res.send(response.message))
.catch((error) => res.status(500).send(error.message));
});
app.listen(port, () => {
console.log(`nodemailerProject is listening at http://localhost:${port}`);
});
there is a button in other js file which run this js script and send email when I push the button:
let input = document.getElementById("phonenumber");
head.addEventListener("click", function () {
fetch("http://localhost:5000/")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
});
there is an imput field for text a message in html file
<input id="phonenumber" class="text-order" type="text"
placeholder="___________"'/>
how to make to send this input value in email message when a button is pressed?
The Fetch API accepts a second parameter, an options object. This is where you would pass your input. In your case, you'll need to capture the value of the input. So if you have:
let input = document.getElementById("phonenumber");
then you should be able to access the value with input.value. If you send that in the body property of your options object, it should show up in the request body on the server.
Something like this:
fetch("http://localhost:5000/", {
body: JSON.stringify(input.value)
})
I see that you're also listening for the click on another element (head). If that's the case, then you'll probably need an onChange handler on the input which stores the value somewhere locally. Then when the user clicks the other element, you have it ready to pass into the fetch options.
Here's an example of the syntax for sending options (borrowed from the docs I shared above), demonstrating the different options it will accept:
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then((data) => {
console.log(data); // JSON data parsed by `data.json()` call
});

how to fetch data from this api using 'POST' method in javascript

url---http://eign-backend.herokuapp.com/property/get-property/17/
Do i have to write complete url like till "/17/" or what!
const response=await fetch('url',{
method:'POST',
body: JSON.stringify(
{
//what should I write here
}
),
headers:{
headers: {'Content-Type':'application/json'},
}
})
const data=await response.json();
console.log(data);
}
First argument in fetch is the actual url
const response=await fetch('http://eign-backend.herokuapp.com/property/get-property/17/',{
method:'POST',
body: JSON.stringify(
{
//what should I write here => write whatever you want to send in this post request's body
}
),
headers:{
headers: {'Content-Type':'application/json'},
}
})
const data=await response.json();
console.log(data);
Consider reading some documentation first
You can directly make a POST request on that URL. It's OK to send a POST request without a body and instead use query string parameters but then it should have been a get request instead of POST if there is no need for the body. But be careful if your parameters contain characters that are not HTTP valid you will have to encode them.
var requestOptions = {
method: 'POST',
redirect: 'follow'
};
fetch("http://eign-backend.herokuapp.com/property/get-property/17/", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
This is the fetch call that I have used.
try this
async function postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});

Transform a post request to a JSON file

I have a questionnaire on javascript(post request) and need to acquire the user's answers and then transform them into a JSON file, so far, I've tried this but I have no idea how to proceed, my code is down below.
exports.answers= (req, res) =>{
async function getISS(){
const response = await fetch(req);
const data =await response.json();
console.log(data);
}
getISS();
console.log(req.text);
let resultado =[data];
res.send(resultado);
};
The answers come from a survey like this
this is the survey
There are a number of ways to send the form data to the server.
const form = document.getElementById('my-form'),
url = 'https://reqres.in/api/users';
form.onsubmit = submit;
function submit(e) {
e.preventDefault();
const formData = new FormData(form),
data = {};
// Get a JSON object from the form data
formData.forEach((value, key) => {
data[key] = value;
});
// Using fetch and await/async
postData(url, data)
.then(res => {
console.log('Fetch await/async response is: ' + JSON.stringify(res)); // JSON data parsed by `response.json()` call
});
// Using fetch / then
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
}).then(
res => res.json()
).then(json => console.log('Fetch / then response is: ' + JSON.stringify(json)));
// Using XMLHttpRequest
const req = new XMLHttpRequest();
req.open('POST', url, true);
req.setRequestHeader('Content-type', 'application/json');
req.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 201) {
console.log('XMLHttpRequest response is: ' + req.response);
}
}
req.send(JSON.stringify(data));
}
/*
* This is the example function on the MDN site for fetch
* https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
*/
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *client
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return await response.json(); // parses JSON response into native JavaScript objects
}
<form action="survey" id="my-form">
<label for="name">Name</label>
<input type="text" name="name" id="name">
<label for="job">Job</label>
<input type="text" name="job" id="job">
<button>Submit</button>
</form>
Any of the above methods should work to send your form data to the server as JSON. I have used an online API to demonstrate.

await not working for async wait fetch to redirect a page

trying to direct to external url by fetch
front end side:
var params
urlFetch(new_url)
.then(params=function() {
var obj=decodeFormParams(params)
console.log("decode value is " + obj); ...
backend side:
export function urlFetch(url ) {
console.log(url );
const request = async () => {
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'no-cors', // no-cors, *cors, same-origin
credentials: 'omit', // include, *same-origin, omit
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8 ',
"Access-Control-Allow-Origin": "*"
},
// body: JSON.stringify() // body data type must match "Content-Type" header
}).then(await function(Response) {
if (Response.ok) {
return Response.text();
}
else {
return Promise.reject("Fetch did not succeed");
}
} )
}
}
CONSOLE.LOG IS:
https://icom.yaad.net/cgi-bin/yaadpay/yaadpay3new.pl?action=pay&PassP=pb&Masof=4500563228&sendemail=True&UTF8=True&UTF8out=True&ClientName=ASG&ClientLName=Shg&cell=&email=SGD&Amount=500&Info=%D7%91%D7%99%D7%AA%20%D7%97%D7%91%22%D7%93%20%D7%A7%D7%A1%D7%A8%20%D7%93%D7%99%D7%95%D7%95%D7%99&tmp=8&Coin=1&PageLang=HEB&Postpone=False&Tash=36&FixTash=True&SendHesh=True
returend value is function params() {
console.log("returend value is " + _params);
var obj = decodeFormParams(_params);
console.log("decode value is " + obj);
AS YOU CAN SEE THE URL IS CORRECT AND SUPPOSE TO REDIRECT TO THAT PAGE BUT NOTING HAPPENDS AND THE FUNCTION DOESNT WAIT
If IT DIDNT WORK WhY IM NOT GETTING THE LOG OF THE ERROR:
else {
return Promise.reject("Fetch did not succeed");
im sending parameters to a page for payment system and the user has to fill the card info there and if it succeeds i should get code=0 as results but nothing hapends

Limit fetch results from javascript fetch

Is there a function similar to q=sort& or q=created:& to limit number of results from a JavaScript fetch?
fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => res.json())
.then((data) => { }
The best solution, of course, is if the https://jsonplaceholder.typicode.com/posts endpoint documents a limit or filter parameter you can send it.
Assuming the result is an array, or contains an array, the very-much-second-best solution is to filter the result (to apply criteria) and/or slice the result (to just apply a limit):
fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => res.json())
.then((data) => {
data = data.filter(entry => entry.created > someValue) // Created after X
.slice(0, 1000); // Limit to 1000
// ...use data...
})
.catch(error => { // <=== Don't forget to handle errors
// Handle error...
});
Note: Your fetch call is missing a check on res.ok (it's not just you, a lot of people make that mistake so many that I wrote it up on my anemic little blog):
fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => { // ***
if (!res.ok) { // ***
throw new Error("HTTP error " + res.status); // ***
} // ***
}) // ***
.then((res) => res.json())
.then((data) => {
data = data.filter(entry => entry.created > someValue)
.slice(0, 1000);
// ...use data...
})
.catch(error => {
// Handle error...
});
From https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch:
postData(`http://example.com/answer`, {answer: 42})
.then(data => console.log(JSON.stringify(data))) // JSON-string from `response.json()` call
.catch(error => console.error(error));
function postData(url = ``, data = {}) {
// Default options are marked with *
return fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, same-origin, *omit
headers: {
"Content-Type": "application/json; charset=utf-8",
// "Content-Type": "application/x-www-form-urlencoded",
},
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
body: JSON.stringify(data), // body data type must match "Content-Type" header
})
.then(response => response.json()); // parses response to JSON
}
Not sure what exactly you want so here are 3 possibilities:
You can add a payload to the body of the fetch, see above.
You could simply url-encode it.
On res.json()) .then((data) => { } ... You can filter the data you want.
Hope this helps.

Categories