Issues sending requests using fetch - laravel

I am using FETCH to make GET requests. I am also using NGROK for HTTP tunneling. My problem is here when I use var url = 'http://localhost:9090/test-message', I get a response but when I use
https://c2f2493e.ngrok.io/test-message I don't get a response. I don't know what the problem might be here.
Here is the full code:
fetch(url).then(function(response) {
console.log(response)
})

This url var url = 'http://localhost:9090/test-message ' does not have any Get Method request.
You May try Like this
function myFunction() {
var str = "http://localhost:9090/test-message";
var res = str.split("/");
res = res.reverse();
alert(res[0]); //text-message
}

Related

URLS Redirects with Cypress automation

I passed 100+ URLs path(legacy) in the scenario outlines and i want to hit each one of them and to redirect to a new path(new).
I passed a code like below;
function createNewUrlFromLegacy(legacyPageUrl) {
const urlPath = legacyPageUrl.split('/');
let newUrl;
if (urlPath.length == 7) {
newUrl = 'new-homes/' + urlPath[5];
} else {
newUrl = 'new-homes/' + urlPath[0];
}
return newUrl
}
I passed this following in my stepDef file
const expectedUrl = createNewUrlFromLegacy(legacyUrl);
cy.url().should('include', expectedUrl);
And it run successfully.
But i want to use response code 301 as an assertion instead relying on expectedUrl only.
How can i do this pls?.
I have managed to get it working using the following steps;
First visit the legacy url and then set followRedirects: false using alias.
cy.visit(legacyUrl);
cy.request({url: legacyUrl, followRedirect: false}).as('response');`
cy.get('#response').its('status').should('eq', 301); --> Assert Response code is 301
cy.get('#response').its('redirectedToUrl').should('contain', expectedUrl); -->Assert expected URL is displayed.

Does Google Script have an equivalent to python's Session object?

I have this python script and I want to get Google Script equivalent but I do not know how to "pass" whatever needs to be passed between next get or post request once I log in.
import requests
import json
# login
session = requests.session()
data = {
'LoginName': 'name',
'Password': 'password'
}
session.post('https://www.web.com/en-CA/Login/Login', data=data)
session.get('https://www.web.com//en-CA/Redirect/?page=Dashboard')
# get customer table
data = {
'page': '1',
'pageSize': '100'
}
response = session.post('https://www.web.com/en-CA/Reporting', data=data)
print(response.json())
I wonder if there is an equivalent to .session() object from python's requests module. I did search google but could not find any working example. I am not a coder so I dot exactly know that that .session() object does. Would it be enough to pass headers from response when making new request?
UPDATE
I read in some other question that Google might be using for every single UrlFetchApp.fetch different IP so login and cookies might not work, I guess.
I believe your goal as follows.
You want to achieve your python script with Google Apps Script.
Issue and workaround:
If my understanding is correct, when session() of python is used, the multiple requests can be achieved by keeping the cookie. In order to achieve this situation using Google Apps Script, for example, I thought that the cookie is retrieved at 1st request and the retrieved cookie is included in the request header for 2nd request. Because, in the current stage, UrlFetchApp has no method for directly keeping cookie and using it to the next request.
From above situation, when your script is converted to Google Apps Script, it becomes as follows.
Sample script:
function myFunction() {
const url1 = "https://www.web.com/en-CA/Login/Login";
const url2 = "https://www.web.com//en-CA/Redirect/?page=Dashboard";
const url3 = "https://www.web.com/en-CA/Reporting";
// 1st request
const params1 = {
method: "post",
payload: {LoginName: "name", Password: "password"},
followRedirects: false
}
const res1 = UrlFetchApp.fetch(url1, params1);
const headers1 = res1.getAllHeaders();
if (!headers1["Set-Cookie"]) throw new Error("No cookie");
// 2nd request
const params2 = {
headers: {Cookie: JSON.stringify(headers1["Set-Cookie"])},
followRedirects: false
};
const res2 = UrlFetchApp.fetch(url2, params2);
const headers2 = res2.getAllHeaders();
// 3rd request
const params3 = {
method: "post",
payload: {page: "1", pageSize: "100"},
headers: {Cookie: JSON.stringify(headers2["Set-Cookie"] ? headers2["Set-Cookie"] : headers1["Set-Cookie"])},
followRedirects: false
}
const res3 = UrlFetchApp.fetch(url3, params3);
console.log(res3.getContentText())
}
By this sample script, the cookie can be retrieved from 1st request and the retrieved cookie can be used for next request.
Unfortunately, I have no information of your actual server and I cannot test for your actual URLs. So I'm not sure whether this sample script directly works for your server.
And, I'm not sure whether followRedirects: false in each request is required to be included. So when an error occurs, please remove it and test it again.
About the method for including the cookie to the request header, JSON.stringify might not be required to be used. But, I'm not sure about this for your server.
Reference:
Class UrlFetchApp
You might want to try this:
var nl = getNewLine()
function getNewLine() {
var agent = navigator.userAgent
if (agent.indexOf("Win") >= 0)
return "\r\n"
else
if (agent.indexOf("Mac") >= 0)
return "\r"
return "\r"
}
pagecode = 'import requests
import json
# login
session = requests.session()
data = {
\'LoginName\': \'name\',
\'Password\': \'password\'
}
session.post(\'https://www.web.com/en-CA/Login/Login\', data=data)
session.get(\'https://www.web.com//en-CA/Redirect/?page=Dashboard\')
# get customer table
data = {
\'page\': \'1\',
\'pageSize\': \'100\'
}
response = session.post(\'https://www.web.com/en-CA/Reporting\', data=data)
print(response.json())'
document.write(pagecode);
I used this program

GET request from NetSuite to Oracle EPM, but faced with "Authorization Required - You are not authorized to access the requested resource

Error: "Authorization Required - You are not authorized to access the requested resource. Check the supplied credentials (e.g., username and password)."
Using the same exact headers and URL, I am successfully able to make the request get through via Postman and Powershell. But when doing the call via SuiteScript, I get the auth error. I am thinking it may have something to do with me constructing the headers.
Here is the code I used via NetSuite Debugger:
require(['N/https', 'N/encode'], function(https, encode) {
function fetchCSVdata() {
var authObj = encode.convert({
string : "username:password",
inputEncoding : encode.Encoding.UTF_8,
outputEncoding : encode.Encoding.BASE_64
});
var psswd = 'Basic ' + authObj;
var headerObj = {'Authorization' : psswd};
var response = https.get({
url: 'https://<bleep>.pbcs.us6.oraclecloud.com/interop/rest/11.1.2.3.600/applicationsnapshots/DemandPlan_ExportItemPlan.csv/contents',
headers: headerObj
});
return response.body;
};
var x = fetchCSVdata();
log.debug("error", x);
});
Looking at some working code of mine it is different than yours but I don't see the error.
var authstring = encode.convert({string: 'username:password',
inputEncoding: encode.Encoding.UTF_8,
outputEncoding: encode.Encoding.BASE_64});
var headerObj = {Authorization: 'Basic '+ authstring };
var response = https.get({url: 'https://webservices.XXX.com', headers: headerObj});

Get-Record-API request not working any more

since last week, the Get-Record API-Endpoint is not working any more. Please check out the node.js snippet and the screenshot at the end.
Getting the list of keys in the store is working (first request). But getting the records, results in chaos (second request). It's the same result, if an explizit 'Accept-Encoding: gzip' is added. Could you please verify?
Cheers Wulfgäääng
const request = require('request-promise-native');
const storeUrl = 'https://api.apify.com/v2/key-value-stores/z9UOmIgYF7oMxXkGS/';
(async () => {
var results = await request({uri: `${storeUrl}keys`, json: true});
console.log('Keys:');
console.dir(results);
results = await request({uri: `${storeUrl}records/testkey`, json: true});
console.log('Record:');
console.dir(results);
})();
great, it's working.
Unfortunatelly, I am not using node.js for my purpose (a local watchdog). I am using Autohotkey, which takes advantage of Windows 'WinHttpRequest.5.1' (see below).
Do you know, who to force 'WinHttpRequest.5.1' using 'gzip' decoding? 'Accept-Encoding: gzip' doesn't work either (see below).
Cheers Wulfgäääng
storeUrl := "https://api.apify.com/v2/key-value-stores/z9UOmIgYF7oMxXkGS/"
whr1 := ComObjCreate( "WinHttp.WinHttpRequest.5.1")
whr1.Open("GET", storeUrl . "keys", true)
whr1.SetRequestHeader("Accept-Encoding", "gzip")
whr1.Send()
whr1.WaitForResponse()
response := whr1.ResponseText
whr2 := ComObjCreate( "WinHttp.WinHttpRequest.5.1")
whr2.Open("GET", storeUrl . "records/testkey", true)
whr2.SetRequestHeader("Accept-Encoding", "gzip")
whr2.Send()
whr2.WaitForResponse()
response := whr2.ResponseText
You are right, the response returns gzipped body. It is an issue on Apify API. You can force gzip headers using gzip: true parameter in your request like:
EDIT: It was fixed on Apify site. You need to add disableRedirect=true parameter to request URL as well.
const request = require('request-promise-native');
const storeUrl = 'https://api.apify.com/v2/key-value-stores/z9UOmIgYF7oMxXkGS/';
(async () => {
var results = await request({uri: `${storeUrl}keys`, json: true, resolveWithFullResponse: true});
console.log('Keys:');
console.dir(results.headers);
results = await request({uri: `${storeUrl}records/testkey?disableRedirect=true`, json: true, gzip: true });
console.log('Record:');
console.dir(results.headers);
})();

Asynchronous form-data POST request with xmlhhtprequest

I am trying to upload a file to the REST Api of Octoprint, which should be done by sending a POST request with Content-Type: multipart/form-data
(http://docs.octoprint.org/en/master/api/fileops.html#upload-file)
I am using NodeJS and two libraries, XmlHttpRequest and form-data. When trying:
var xhr = new xmlhttprequest() ;
var form = new formData() ;
form.append('exampleKey', 'exampleValue');
xhr.open("POST","octopi.local/api/local", true) ;
xhr.setRequestHeader("Content-Type","multipart/form-data") ;
xhr.send(form) ;
I get an error at the xhr.send line :
TypeError: first argument must be a string or Buffer
If I make a synchronous request by using xhr.open("POST",url,false), this error disappears.
Why is it so ? Is there a way to turn it into an asynchronous request ?
EDIT Actually, I don't really understand the documentation. I suppose that I should set the file I want to upload by using form.append("filename", filepath, "exampleName"), but I am not sure about that. The fact is that I noticed that I get the TypeError even if I try a simplified request, without sending any file.
EDIT2 This is the modified code, which returns the same error :
var XMLHttpRequest=require('xmlhttprequest').XMLHttpRequest ;
var FormData = require('form-data');
var data = new FormData();
data.append("key","value" );
var xhr = new XMLHttpRequest();
xhr.open('POST', "octopi.local/api/files/");
xhr.send(data);
After a long time working on this, I finally managed to upload a file. If you use NodeJS, don't rely on the MDN documentation: it tells what the libraries should do, not what they can actually do on the node platform. You should only focus on the docs available on GitHub.
It seems that it is not currently possible to send a form with XMLHttpRequest : I tried using JSON.stringify(form) but then wireshark tells me that the request is not a multipart/formdata request.
If you want to upload a file, you should rather use the 'request' module. The following has worked for me :
exports.unwrappeduploadToOctoprint = function(){
"use strict" ;
var form ={
file: {
value: fs.readFileSync(__dirname+'/test2.gcode'),
options: { filename: 'test2.gcode'}
}
};
var options = {
method: 'POST',
url: 'http://192.168.1.24/api/files/local',
headers: { 'x-api-key': 'E0A2518FB11B40F595FC0068192A1AB3'},
formData: form
};
var req = request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
};
Seems that you have some typos in your code. Use code snippet below instead. Replace the relevant parts according to your needs
var fileToUpload = document.getElementById('input').files[0];
var data = new FormData();
data.append("myfile", fileToUpload);
var xhr = new XMLHttpRequest();
xhr.open('POST', "upload_endpoint");
xhr.send(data);

Resources