Fetch Query Parameters [duplicate] - javascript

This question already has an answer here:
How do I parse a URL for a specific Query Paramter in javascript?
(1 answer)
Closed 2 years ago.
I need to fetch authorization code from the URL . It is present as a query string parameters.
When I run the belowo URL
https://XXX.authenticaion.com/oauth/authorize?response_type=code&client_id=sb!t113
It redirects to
http://localhost:8080/?code=8wFgU1GJo3
I need to parse the localhost URL and fetch the code.
Please help on how to retrieve the code
Code :
const url = 'https://XXX.authenticaion.com/oauth/authorize?response_type=code&client_id=sb!t113'
const config = {
method: "GET"
};
const response = await fetch(url ,config);
console.log('Response Text...............'+response.text())

You could use plain js URL web api to create URL object and then get the code value.
const url = 'http://localhost:8080/?code=8wFgU1GJo3'
const code = new URL(url).searchParams.getAll('code')
console.log(code)

Related

Google App Scripts ReferenceError: URLSearchParams is not defined [duplicate]

This question already has answers here:
ReferenceError: Headers is not defined in Google scripts
(1 answer)
How to get an audio response from an API call within google app to play in speakers
(1 answer)
FileReader not defined in Apps Script
(1 answer)
How to use payload with method get?
(1 answer)
Which JavaScript features are available in Google Apps scripts?
(1 answer)
Closed 4 months ago.
This post was edited and submitted for review 4 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I am trying to access an API in an apps scripts function. I have tested my code in VS code and it works just fine, but when I run it in apps scripts, I get an error saying "ReferenceError: URLSearchParams is not defined". Does anyone know of a fix? None of the similar questions offer a viable solution.
Code:
async function ApiTest() {
let status = "watching";
let num_watched_episodes = 10;
let token = "MyTokenIsHere";
let id = 50346;
const urlParams = new URLSearchParams({
status: status,
num_watched_episodes: num_watched_episodes,
});
fetch('https://api.myanimelist.net/v2/anime/' + id + '/my_list_status', {
method: "PATCH",
headers: {
'Authorization': 'Bearer ' + token,
},
body: urlParams,
})
}

How to handle CORS problems using Apps Scrips in React? [duplicate]

This question already has answers here:
Error Request to Google App script Translate API using Axios Vue js 3
(2 answers)
Closed 6 months ago.
I just want make my react send and receive data for a private sheets, using some credential for this if necessary, my project is a site with interesting forms for workers and my boss want see these answers in google sheets. I already tried this:
Sheets API using Node Js, but i can't put Node in my project and dont know how to use this.
Sheets API using JS on React but i take a lot of strange libraries to make the #1 work, not happen.
Google Apps Script, my last one attempt, i make one function to take data, transform this data on JSON file and return that. All rigth with this, i guess, but when i try use this function on react a wild bug appears: CORS policy.
Error:
localhost/:1
Access to XMLHttpRequest at 'https://script.google.com/macros/s/AKfycbxuz7xwcOu77AqEsAnnOS0MeQ2qu5D47ZnGRhMS3su_OegiNeyyFdoY3cK3svybyBZb/exec' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My JS code:
const obj = {
redirect: "follow",
method: "POST",
headers: {
'Access-Control-Allow-Origin': '*',
"Content-Type": "text/plain;charset=utf-8",
},
};
const url = "https://script.google.com/macros/s/AKfycbxuz7xwcOu77AqEsAnnOS0MeQ2qu5D47ZnGRhMS3su_OegiNeyyFdoY3cK3svybyBZb/exec";
axios.get(url, obj)
.then((response) => {
console.log(response);});
My Apps Script code:
function doGet(e) {
const ss = SpreadsheetApp.openById("1Qo78FwRfUBE20q3uJO4me-I30yd9IO64_cf48OER2Qk").getSheetByName("pag1");
const values = ss.getDataRange().getValues();
//Headers
const headers = values[0];
//Values
const info = values.slice(1);
const holder = [];
info.forEach((ele, ind)=>{
const temp = {};
headers.forEach((header,index) =>{
header = header.toLowerCase();
temp[header] = ele[index];
});
holder.push(temp);
});
Logger.log(holder);
const output = JSON.stringify({
status: true,
data: holder
});
return ContentService.createTextOutput(output).setMimeType(ContentService.MimeType.JSON);
}
Script dev link: https://script.googleusercontent.com/macros/echo?user_content_key=sznzc94eVNLBu3aIH1EF1AQzuKbRbFsIrDm9SpEcspMuOGcCWD0DQpYUFXf_-EDdOUBEToRFCd8Toi2pg73mnseCZUFc__HHm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnFFyHLiy6APruhip6byWAMZqTnK1bODOhKFDg3M9dJJF-C53vkZT1WCZ_kcKr-1V1Q&lib=MWvmhuupDFy3ZSGL-SCi1vYvpuuAzsMhg
If i put code:"no-cors" the res no have my data. What am i doing wrong?
install cors
npm install cors --save
and just add these lines in your main file where your request is going.
const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors());

How to retrieve query parameters from GET request using javascript? [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 12 months ago.
Below is my GET request. I am trying to retrieve the client_id and redirect_uri parameters.
https://sdkapp.example.com:8443/central-login/index.html?client_id=dtvClient&redirect_uri=https://www.example3.com:443/callback
And then utilize those values, in a embedded js script within the same html page.
Config.set({
clientId: //fetched query parameter for client_id
redirectUri: // fetched query parameter for redirect_uri
});
If this is on the client you can use URL and searchParams
// const url = new URL(location.href); // uncomment and delete next line
const url = new URL("https://sdkapp.example.com:8443/central-login/index.html?client_id=dtvClient&redirect_uri=https://www.example3.com:443/callback"); // for example
const obj = {
"clientId": url.searchParams.get("client_id"),
"redirectUri": url.searchParams.get("redirect_uri")
};
console.log(obj)
// Config.set(obj)
If on the server: for example node also has URL
And here is an answer for php: Get URL query string parameters

express can`t get query param from url [duplicate]

This question already has answers here:
How to get GET (query string) variables in Express.js on Node.js?
(26 answers)
Closed 4 years ago.
I use express framework and react on front app for manage http request on node app. A have method :
app.get('/api/matches', async (req, res) => {
console.log(req.originalUrl); // /api/matches/
console.log(req.query); // {}
...
when I use url like http://localhost:3000/matches?id=123 I expect to get id inside req.query object but instead I get empty {} object. Also I tried to check how express see url using originUrl object, its return without query ?id=123.
You need to use your URL like http://localhost:3000/api/matches/?id=123. Notice that api word. This is because your GET route has /api/matches and request will look for path /api/matches. Doing that change will work for you. Then with that change you will be able to get req.query as {id: 123}

Get page URL parameters from a service worker

How do I get page URL with parameters from a service worker?
I have tried self.registration.scope but that doesn't include the parameters.
I'm not clear as to whether you're asking about getting the service worker script's URL, or the URLs of all of the client pages that are open under the service worker's scope. So... here's how to do both:
// Get a URL object for the service worker script's location.
const swScriptUrl = new URL(self.location);
// Get URL objects for each client's location.
self.clients.matchAll({includeUncontrolled: true}).then(clients => {
for (const client of clients) {
const clientUrl = new URL(client.url);
}
});
In either of those cases, once you have a URL object, you can use its searchParams property if you're interested in the query parameters:
if (url.searchParams.get('key') === 'value') {
// Do something if the URL contains key=value as a query parameter.
}
You can get waiting.scriptURL or active.scriptURL, pass result to URL() constructor, get .search property of object
navigator.serviceWorker.register("sw.js?abc=123")
.then(function(reg) {
const scriptURL = reg.waiting && reg.waiting.scriptURL || reg.active.scriptURL;
const url = new URL(scriptURL);
const queryString = url.search;
console.log(queryString);
}).catch(function(err) {
console.log("err", err);
});
ServiceWorker.scriptURL can give you the URL and its parameters as well.
Then, the following step is to get a ServiceWorker object, and it depends on where you would like to use the URL parameters.
In the worker script, use self.serviceWorker.scriptURL. e.g.
const searchParams = new URLSearchParams(self.serviceWorker.scriptURL);
In the page script, use scriptURL with navigator.serviceWorker.ready. e.g.
const serviceWorkerRegistration = await navigator.serviceWorker.ready;
const activeServiceWorker = serviceWorkerRegistration.active;
const searchParams = new URLSearchParams(activeServiceWorker.scriptURL);
However, you might want to get a registration object from register API, but the above code snippet should work as well.

Categories

Resources