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

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,
})
}

Related

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

Require is not define [duplicate]

This question already has answers here:
Javascript require() function giving ReferenceError: require is not defined
(6 answers)
Closed 2 years ago.
when I tried to send an email using nodemailer, after I insert these into my web project, and I get an error "require is not defined". Can I know how to solve it?
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service:'gmail',
auth:{
user:'xxx#gmail.com',
pass:'xxxxxxx'
}
});
var mailOptions = {
from:'xxx#gmail.com',
to: 'xxx#gmail.com',
subject:'Thanks for using!',
text:'Thanks!'
};
transporter.sendMail(mailOptions,function(error, info){
if(error){
console.log(error);
}else
console.log('Email sent: '+ info.response);
});
I am assuming you are trying to do this on the frontend. Nodemailer is a package that is made to be run on a backend node.js server. You do not have node listed for the questions tags so that is why I am assuming this. If this is not the case then check out:
http://requirejs.org/docs/download.html
Add this to your project: https://requirejs.org/docs/release/2.3.5/minified/require.js
and take a look at this http://requirejs.org/docs/api.html

Fetch Query Parameters [duplicate]

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)

using twitter api with firebase cloud functions [duplicate]

This question already has an answer here:
Firebase Cloud Functions throws a DNS error when calling an external API [duplicate]
(1 answer)
Closed 4 years ago.
I have been assigned on a task to fetch all tweets from a certain hashtag and send that data to my application. So I decided to use firebase cloud functions, I generated the key needed for the twitter api. I also tested get my homepage using postman status and worked, however my issue now when I test my code on good cloud functions I cant get it to work and the error message when I try this end point:
Error: could not handle the request
https://us-central1-don.cloudfunctions.net/api/
or
https://us-central1-don.cloudfunctions.net/api/statuses/user_timeline
and this is my code on firebase cloud functions
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const Twitter = require('twitter');
admin.initializeApp(functions.config().firebase);
const client = new Twitter({
consumer_key: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
consumer_secret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
access_token_key: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
access_token_secret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
});
const app = express();
/* Express */
app.get('/', function(req,res){
client.get('statuses/user_timeline', {screen_name: 'nodejs', count: 5}, function (error, tweets, response) {
if (!error) {
response.send({ title: 'Express', tweets: tweets })
}
else {
response.send({ error: "this is error: " + error })
}
});
});
// Cloud Function
exports.api = functions.https.onRequest(app)
Hope anyone can suggest any solutions, thanks.
Update: here is my function console where it also throws an error:
api Function execution took 8 ms, finished with status code: 404
api Billing account not configured. External network is not accessible
and quotas are severely limited. Configure billing account to remove
these restrictions
As mentioned in the comments, you should upgrade to a paid plan, you may find this other Stack Overflow question useful : Cloud Functions for Firebase - Billing account not configured
Hope this helps!

Login with Facebook-accounts (Meteor) doesn't work [duplicate]

This question already has an answer here:
facebook graph api not work from 2.2 to 2.3
(1 answer)
Closed 5 years ago.
I ever used login with accounts-facebook with Meteor, but it stopped working without changing anything.
Here a snippet from my login code:
static Facebook() {
if(Meteor.user()) {
Meteor.call('permissionsServicesController', 'facebook');
}
if (Meteor.isCordova) {
facebookConnectPlugin.login(
['email'],
function () {
console.log('success');
},
function () {
console.log('error');
}
);
}
else {
Meteor.loginWithFacebook({
loginStyle: 'redirect',
requestPermissions: ['email', 'publish_actions', 'user_about_me', 'user_birthday', 'user_education_history', 'user_friends', 'user_likes', 'user_location',
'user_photos', 'user_posts', 'user_relationships', 'user_religion_politics', 'user_videos', 'user_website', 'user_work_history',
'manage_pages', 'publish_pages']
}, function (e) {
if (e) console.log('Error at loginWithFacebook',e);
});
}
}
And the message I'm receiving from terminal:
Exception while invoking method 'login' Error: Failed to complete OAuth handshake with Facebook.
I'm using:
accounts-facebook#1.0.1
Meteor 1.4.1.1
I already tried to take out the authorization account from facebook, check all the permissions, etc.
Anyone can help me?
I had a similar issue recently. Check is your accounts-facebook package version.
According to Facebook Graph API Changelog, version 2.2 would be available until March 25th. (https://developers.facebook.com/docs/apps/changelog)
Update your accounts-facebook atmosphere package by running meteor update and this will make sure that your authentication process is using a recent version of the Graph API.
That should fix your OAuth handshake problem.

Categories

Resources