Trying to get info from each Google result in Chrome Extension - google-chrome-extension

I'm trying to use the urls from a Google results page to get info of each url, using a Chrome Extension I developed.
const items = document.querySelectorAll('div[jscontroller][jsaction][data-ved]');
var api = 'https://myapi.test';
var n = 0;
items.forEach(item => {
var url = item.querySelector('a');
if (url == null)
return;
var href = url.getAttribute("href");
if (href == null || href.startsWith('/search') || href.includes('#') || href.startsWith('/preferences'))
return;
fetch(api + 'url_info', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'url': encodeURIComponent(href)
})
})
.then(function(res) {
//wait for response..
if (res.status !== 200) {
console.log(res);
return;
}
})
.catch(function (error) {
console.error(error);
});
});
My manifest looks like this :
{
"manifest_version": 2,
"name": "Test",
"description": "Test extension",
"version": "1.0.0",
"permissions": [
"https://myapi.test/*",
"tabs",
"notifications"
],
"icons": {
"128" : "img/icon_128.png"
},
"content_scripts": [
{
"js": ["content_script.js"],
"matches": ["https://www.google.com/search*"]
}
]
}
I get the url of each result but can't actually use them in order to fetch info.
Either I get a CORS policy block from Google, either I get empty results using the method "no-cors" :
"Access https://myapi.test from origin 'https://www.google.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check".
Do I miss something important to pass this CORS policy that prevent me from using fetch ?
Thanks

Related

Node js if status of http post request is 401 then execute another post request

I have the below https post request, which is very simple. The code works as expected when using an active token. when using an expired token it receives a 401 error. This is ok. I would like to run a diiferent post request if i receive a 401.
what code can I add to make it check for 401 status and run a different post request? I'm new to node js. Should I use a function? promise?
const https = require('https');
const postData = JSON.stringify({
"data": [
{
"Company": "Test Company",
"Last_Name": "test",
"First_Name": "test",
"Email": "test#gmail.com",
}
],
"trigger": [
"test"
]
});
const options = {
method: 'POST',
hostname: 'www.host.com',
path: '/crm/xxx',
headers: {
'Authorization': 'oauthtoken 1000.xxxxxxxxxxxxx',
'Content-Type': 'application/json',
'Content-Length': postData.length
}
};
const req = https.request(options, (res) => {
console.log('Status Code:', res.statusCode);
if (res.statusCode == '401'){
// run other post request here? somewhere else?
console.log('rec 401 status code');
}else{
console.log('did not rec 401');
}
}).on("error", (err) => {
console.log("Error: ", err.message);
});
req.write(postData);
req.end();

POST request with JSON payload with NodeJS

I'm trying to hit the Intercom API to retrieve a list of conversations and I can't figure out what's wrong. Here is the code:
const request=require('request')
const search_intercom=(admin_id, callback) => {
const options = {
url: 'https://api.intercom.io/conversations/search',
method: 'POST',
headers: {
Authorization: 'Bearer <token>'
},
json: {
query: JSON.stringify({
"field": "teammate_ids",
"operator": "=",
"value": admin_id
})
}
};
request(options, (error, {body} = {}) => {
if (error) {
callback('unable to connect to intercom API', undefined)
} else if (body.length === 0) {
callback('something went wrong', undefined)
} else {
callback(undefined, {
conversation_id: body.conversations[0].id,
client_name: body.conversations[0].source.author.name
})
console.log(body)
}
})
}
module.exports = search_intercom
I was able to wire it up correctly with the web server, so when I debug, options.json.query.admin_id does contain a valid id.
It breaks and says
conversation_id: body.conversations[0].id,
TypeError: Cannot read property '0' of undefined
Here is the content of the body response:
{
type: 'error.list',
request_id: '<some request_id>',
errors: [ { code: 'server_error', message: 'Server Error' } ]
}
Where should I look? I've tried a few different variations of options for sending the payload and I am guessing this is the issue, but I can't find the winning formula...
It looks like I got the body all wrong.
options should look like this instead:
const options = {
url: 'https://api.intercom.io/conversations/search',
method: 'POST',
headers: {
Authorization: 'Bearer <token>'
},
json: true,
body: {
query: {
"field": "teammate_ids",
"operator": "=",
"value": JSON.stringify(admin_id)
}
}
};

Show json url to messenger bot

I want to show data from JSON URL on my facebook messenger bot. I've tried with a lot of code approach. However, I couldn't still get it. I just could show the data the terminal with console.log.
This is the code I use to get data from JSON URL:
const ambilDataProfil = (sender_psid) => {
//sorry this url below is not valid I write intentionally for my privacy data.
request({
url: 'https://sorry-url-privately.firebaseio.com/server/saving-data/users.json',
method: "GET",
}, function(error, response, body){
let jsonBody = JSON.parse(response.body);
let resp = jsonBody.Ndus;
console.log(resp);
let respon = {"text": "resp"};
callSendAPI(sender_psid, respon);
}
// console.log(body.Ndus.goldar);
);
};
function callSendAPI(sender_psid, response) {
// Construct the message body
let request_body = {
"recipient": {
"id": sender_psid
},
"message": response
}
// Send the HTTP request to the Messenger Platform
request({
"uri": "https://graph.facebook.com/v2.6/me/messages",
"qs": { "access_token": PAGE_ACCESS_TOKEN },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
console.log('message sent!')
} else {
console.error("Unable to send message:" + err);
}
});
}

Passing array or nested objects in body of request npm

I have to send some parameters of String type along with one array in my body.
But it throws me an error message:
First argument must be String or buffer
Here is my code:
var tokenList = JSON.parse(req.body.tokenList);
var mobParams = {
"tokens": tokenList,
"profile": "<myprofile>",
"notification": {
"title": req.body.title,
"message": req.body.text
}
};
request({
method: "POST",
url: 'https://api.ionic.io/push/notifications',
headers: {
"content-type": "application/json",
"authorization": "Bearer ********"
},
body: (mobParams)
}, function(error, response, body){
console.log('Ionic push error', error);
console.log('IOnic push res', response);
console.log('IOnic push body', body);
if(!error){
return res.send({
code: 1,
message: "success"
});
}else{
return res.send({
code: 0,
message: error
});
}
How can I pass my array inside this object to request npm?
Also, I would like to add that this implementation works pretty fine through front-end but I have separate codebase which requires me to hit multiple FCM requests i.e. in a loop. So I would be happy to have a solution as neither ionic push nor FCM push works
For the FCM push I am trying the code below :
let desktopParams = {
"notification": {
"title": 'Merchant Portal Notifications',
"body": req.body.text
// "click_action" : action
},
"to": '/topics/' + topic
};
request({
method: "POST",
json: true,
url: 'https://fcm.googleapis.com/fcm/send',
headers: {
"content-type": "application/json",
"authorization": "key=****"
},
body: desktopParams
}, function(error, response, body){
console.log('error', error);
console.log('response', response);
console.log('body', body);
//return body;
});
you should try stringifying your tokenList & req.body.text before you join it with with the string (try to log it and post the outcome so that people will have a better idea about the objects...):
var cho = [{name:'john',lname:'cena'},{name:'mary',lname:'jane'}];
var che = {list:[{name:'john',lname:'cena'},{name:'mary',lname:'jane'}],group:'people'}
var mobParams = {
"tokens":JSON.parse(JSON.stringify(cho)),
"profile": "<myprofile>",
"notification": {
"title": "Some title",
"message":JSON.parse(JSON.stringify(che))
}
};
console.log(JSON.stringify(mobParams));//----->{"tokens":[{"name":"john","lname":"cena"},{"name":"mary","lname":"jane"}],"profile":"<myprofile>","notification":{"title":"Some title","message":{"list":[{"name":"john","lname":"cena"},{"name":"mary","lname":"jane"}],"group":"people"}}}
var arr = [{name:'john',lname:'cena'},{name:'mary',lname:'jane'}]
var js = JSON.stringify(arr);
var blabla = {'item':'something',js}
console.log(blabla); //-----> Object {item: "something", js: "[{"name":"john","lname":"cena"},{"name":"mary","lname":"jane"}]"}
var js = JSON.parse(JSON.stringify(arr));
var blabla = {'item':'something',js}
console.log(blabla); //-----> Object {item: "something", js: Array(2)}
var js = JSON.parse(arr);
var blabla = {'item':'something',js}
console.log(blabla); //-----> "SyntaxError: Unexpected identifier"

How to add a file attachment via NodeJS REST request

There's some documentation on the Jira site on how to add an attachment to an issue via a curl request here: https://confluence.atlassian.com/display/JIRAKB/How+to+attach+an+attachment+in+a+JIRA+issue+using+REST+API
This is the code that I used to successfully create an issue:
var request = require("request");
var auth = "Basic " + new Buffer("user:password").toString("base64");
var options = {
uri: 'http://domain.com/rest/api/2/issue/',
headers : {
"Authorization" : auth
},
method: 'POST',
json: {
"fields": {
"project": {
"id": "10000"
},
"summary": summary,
"description": description,
"issuetype": {
"name": "Bug"
},
"customfield_10003": {"value": value}
}
}
};
request(options, function (error, response, body) {
if (!error) {
console.log("Success");
}
});
So in order to add an attachment to a ticket with the ID of 1200, I would think I would do something like this:
var options = {
uri: 'http://domain.com/rest/api/2/issue/1200/attachment/',
headers : {
"Authorization" : auth,
"X-Atlassian-Token" : nocheck
},
method: 'POST',
json: {
"fields": {
"file" : "filename.txt"
}
}
};
But have had no luck.
Edit: Getting somewhere. Here's what I've got:
var request = require('request');
var fs = require("fs");
var auth = "Basic " + new Buffer("user:password").toString("base64");
var formData = {
file: {
value: fs.createReadStream('file.txt'),
options: {
filename: 'file.txt',
contentType: 'text/plain'
}
}
};
request.post({
url:'http://domain.com/rest/api/2/issue/14000/attachments/',
headers : {
"Authorization" : auth,
"X-Atlassian-Token" : "nocheck"
},
formData: formData
}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
And it uploads a file called file.txt but when I look at the attachment it prints out a stack trace that starts out like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><status><status-code>500</status-code><stack-trace>java.lang.NullPointerException
at com.atlassian.plugins.rest.common.security.jersey.XsrfResourceFilter.mediaTypeToString(XsrfResourceFilter.java:91)
at com.atlassian.plugins.rest.common.security.jersey.XsrfResourceFilter.isXsrfable(XsrfResourceFilter.java:76)
at com.atlassian.plugins.rest.common.security.jersey.XsrfResourceFilter.filter(XsrfResourceFilter.java:54)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:277)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
You first try:
var options = {
uri: 'http://domain.com/rest/api/2/issue/1200/attachment/',
headers : {
"Authorization" : auth,
"X-Atlassian-Token" : nocheck
},
method: 'POST',
json: {
"fields": {
"file" : "filename.txt"
}
}
};
will not work because as it's not supported. Check Jira attachment documentation
So, probably you need to restructure your formData object to be
var formData = {
file: fs.createReadStream('file.txt'),
};
No need for editing meta data if you don't need them. Also make sure you've got a valid stream of your file.
About stacktrace, I see stack frames related to XSRF despite adding "X-Atlassian-Token" header which doesn't make any sense for me.

Resources