There was an error in evaluating the Pre-request Script - javascript

I'm trying to access the response of my POST request in Postman via Post Request Script.
I added this 2 lines, under Pre-request Script
let response = pm.response.json();
console.log('JSON Response: ',response );
Then, I opened up my Postman console, before hit Send to make my POST request
I kept getting
There was an error in evaluating the Pre-request Script: TypeError: Cannot read property 'json' of undefined
Do I need to enable anything on Postman?

Pre-request scripts are ran before the request is sent. You do not have a response yet.
Try putting your script under the Tests tab, which is ran after a response is received.

In my case, there was a script that was screwing up my request. If you get the postman collection from someone else, check this and try to fix it. (in my case I don't need it so I deleted it)

You can try setting an environment variable, get it and parse it, I was created a POST requests to make a login and get a token to each request.
const echoPostRequest = {
url: pm.environment.get("url_login"),
method: 'POST',
header: 'Content-Type: application/json',
body: {
mode: 'raw',
raw: JSON.stringify({ email: pm.environment.get("user"),password: pm.environment.get("password") })
}
};
pm.sendRequest(echoPostRequest, function (err, res) {
console.log(err ? err : res.json());
pm.environment.set("login_response", res.json());
pm.environment.set("bearer_token", pm.environment.get("login_response").bearer_token);
});

was helping a friend and he had tried to make an adjustment to all requests in the collection.
I found in the documentation, how to remove
https://learning.postman.com/docs/writing-scripts/pre-request-scripts/

Please Make Sure That You Cleared Text Area Of PRE-REQUEST & TESTS TAB
By Clearing Text I Solved This Issue

Check if you SSL was turn off. If isn't, turn off.
Settings >> General >> SSL Certificate Verification

Related

how to call haveibeenpwned api php json v3

im want to call haveibeenpwned v3 API,
here is my code
<script>
$.ajax({
url:"https://haveibeenpwned.com/api/v3/breachedaccount/brian.c#softnet.co.id",
headers: { 'Content-type': 'x-www-form-urlencoded', 'hibp-api-key': 'my-key'},
async: false,
datatype:'application/json',
success:function(data){
alert("a");
},
error:function(data){
console.log(JSON.stringify(data));
}
});
</script>
but i always get this this error at the console
{"readyState":0,"status":0,"statusText":"NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https://haveibeenpwned.com/api/v3/breachedaccount/brian.c#softnet.co.id'."}
pls help me if you ever use haveibeenpwned.com
i already doing this way with another api, this is my first time with headers
i expect the json output
You likely have some other errors in your console too which are more relevant than the one you posted - including, I expect, a CORS-related error.
According to https://haveibeenpwned.com/API/v3#CORS you may have a problem because
"CORS is only supported for non-authenticated APIs".
...and according to https://haveibeenpwned.com/API/v3#Authorisation
Authorisation is required for all APIs that enable searching HIBP by email address...The key is then passed in a "hibp-api-key" header
Therefore the endpoint you are trying to search is one requiring authentication/authorisation and as such you are not allowed to make a CORS (cross-origin ) AJAX request to it.
In conclusion you will need to connect to this API via your server-side code instead.

cURL command to Axios request with json data

I've got this cURL request working perfectly on remote interface just as it should
curl -XGET "https://server.host:8080/peregrine" -d '{"exchanges":["kucoin", "kraken"],"volume":10}' -k
I'm trying to build a little frontend app with Vue.js and need the above converted to an Axios get request.
I've been trying the following so far:
axios({
method: 'get',
url: 'https://server.host/peregrine',
data: {"exchanges":["kucoin", "kraken"],"volume":10}
});
putting params instead of data makes it a URL and remote server says that it received no data.
What am I doing wrong? Thanks.
Likely the problem could be that using GET you cannot pass data like you are doing. You have to pass them as query parameter.
Try to change your call with:
axios.get('https://server.host/peregrine', {
params: {"exchanges":["kucoin", "kraken"],"volume":10}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
GET requests should not have request bodies.
CURL will allow you to make a GET request with one, but XMLHttpRequest and fetch (the HTTP APIs in browsers which axios wraps) will not.
Make a POST request instead. You might need to change the server-side code to support this.
Thanks for your replies!
Indeed there's no way to send data body with axios.get()
We ended up tuning the server side to accept normal generic GET requests. Thanks again to everyone who answered!

RESTful Get Request with Angular & NodeJS Express

I'm just following tutorials and figuring out how to handle get requests in NodeJS.
Here are snippets of my code:
NodeJS:
router.get('/test', function(request, response, next) {
console.log("Received Get Request");
response.jsonp({
data: 'test'
});
});
Angular:
$http.get("http://localhost:3000/test").
success(function(response) {
alert("OK");
}).
error(function(response) {
alert("FAIL");
});
If I try to access the link directly # localhost:3000/test, I'm able to receive the JSON message correctly. But when I use angularJS $http call, the request always fails and I'll find this error in the network inspector (Response)
SyntaxError:JSON.parse:unexpected end of data at line 1 column 1 of
the JSON data
The reason for that is because the response is empty but the response code is 200 in both cases.
I've tried searching for hours but maybe someone can enlighten me on this?
you could try and send
res.send('test')
and then on your http request you can use 'then'
$http.get("http://localhost:3000/test").then(function(res) {
console.log(res);
})
unlike success, then will give you a complete object (with 'test' - string as res.data)
success will bring you only the data;
then will bring you the whole object (with the status and such)..
now about that jsonp .. it's used to override a json response. you could simply use 'res.json({data: 'test'})' and it should also work for you..
hope it helps
You're using jsonp in node, which you probably don't need to. This adds extra characters to the response and so the JSON parser fails to parse (that's what the error is telling you, the JSON is malformed)
Try changing the server to look like
response.json({
data: 'test'
});
If you look in the Network pane of the developer tools, you should be able to see the raw response. It should look something like:
{"data" : "test"}

Cross-domain requests stopped working due to no `Access-Control-Allow-Origin` header present in the response

I have an error reporting beacon I created using Google Apps script and it is published to run as myself and to be accessible to "anyone, even anonymous," which should mean that X-domain requests to GAS are allowed.
However, my browsers are now indicating there is no Access-Control-Allow-Origin header on the response after the code posts to the beacon.
Am I missing something here? This used to work as recently as two months ago. So long as the GAS was published for public access, then it was setting the Access-Control-Allow-Origin header.
In Google Apps Script:
Code.gs
function doPost(data){
if(data){
//Do Something
}
return ContentService.createTextOutput("{status:'okay'}", ContentService.MimeType.JSON);
}
Client Side:
script.js
$.post(beacon_url, data, null, "json");
When making calls to a contentservice script I always have sent a callback for JSONP. Since GAS does not support CORS this is the only reliable way to ensure your app doesn't break when x-domain issues arrive.
Making a call in jQuery just add "&callback=?". It will figure everything else out.
var url = "https://script.google.com/macros/s/{YourProjectId}/exec?offset="+offset+"&baseDate="+baseDate+"&callback=?";
$.getJSON( url,function( returnValue ){...});
On the server side
function doGet(e){
var callback = e.parameter.callback;
//do stuff ...
return ContentService.createTextOutput(callback+'('+ JSON.stringify(returnValue)+')').setMimeType(ContentService.MimeType.JAVASCRIPT);
}
I've lost a couple of hours with the same issue. The solution was trivial.
When you deploy the script as webapp, you get two URLs: the /dev one and the /exec one. You should use /exec one to make cross domain POST requests. The /dev one is always private: it requires to be authorized and doesn't set *Allow-Origin header.
PS.: The /exec one seems to be frozen — it doesn't reflect any changes of code until you manually deploy it with a new version string (dropdown list in deploy dialog). To debug the most recent version of the script with the /dev URL just install an alternative browser and disable it's web-security features (--disable-web-security in GoogleChrome).
Just to make it simpler for those who are only interested in a POST request like me:
function doPost(e){
//do stuff ...
var MyResponse = "It Works!";
return ContentService.createTextOutput(MyResponse).setMimeType(ContentService.MimeType.JAVASCRIPT);
}
I stumbled upon the same issue:
calling /exec-urls from the browser went fine when running a webpage on localhost
throws crossorigin-error when called from a https-domain
I was trying to avoid refactoring my POST JSON-clientcode into JSONP (I was skeptical, since things always worked before).
Possible Fix #1
Luckily, after I did one non-CORS request (fetch() in the browser from a https-domain, using mode: no-cors), the usual CORS-requests worked fine again.
last thoughts
A last explanation might be: every new appscript-deployment needs a bit of time/usage before its configuration actually settled down at server-level.
Following solution works for me
In Google Apps Script
function doPost(e) {
return ContentService.createTextOutput(JSON.stringify({status: "success", "data": "my-data"})).setMimeType(ContentService.MimeType.JSON);
}
In JavaScript
fetch(URL, {
redirect: "follow",
method: "POST",
body: JSON.stringify(DATA),
headers: {
"Content-Type": "text/plain;charset=utf-8",
},
})
Notice the attribute redirect: "follow" which is very very important. Without that, it doesn't work for me.
I faced a similar issue of CORS policy error when I tried to integrate the app script application with another Vue application.
Please be careful with the following configurations:
Project version should be NEW for every deployment.
Execute the app as me in case you want to give access to all.
Who has access to the app to anyone, anonymous.
Hope this works for you.
in your calling application, just set the content-type to text/plain, and you will be able to parse the returned JSON from GAS as a valid json object.
Here is my JSON object in my google script doPost function
var result = {
status: 200,
error: 'None',
rowID: rowID
};
ws.appendRow(rowContents);
return ContentService.createTextOutput(JSON.stringify(result))
.setMimeType(ContentService.MimeType.JSON);
and here I am calling my app script API from node js
const requestOptions = {
method: 'POST',
headers: {'Content-Type': 'text/plain'},
body: JSON.stringify({param1: value, param2:value})
};
const response = await fetch(server_URL, requestOptions);
const data = await response.json();
console.log(data);
console.log(data.status);
My case is different, I'm facing the CORS error in a very weird way.
My code works normally and no CORS errors, only until I added a constant:
const MY_CONST = "...";
It seems that Google Apps Script (GAS) won't allow 'const' keyword, GAS is based on ES3 or before ES5 or that kind of thing. The error on 'const' redirect to an error page URL with no CORS.
Reference:
https://stackoverflow.com/a/54413892/5581893
In case this helps all any of those people like me:
I have a .js file which contains all my utility functions, including ones which call a GAS. I keep forgetting to clear my cache when I go to test updates, so I'll often get this kind of error because the cached code is using the /dev link instead of the /exec one.

Firefox addon sdk Request module POST method with payload

I need to do a POST method inside a firefox add-on to another server, I have been trying to use different ways, and after googling I found out that I should use the Request module from the SDK inside my main.js.
I am using firefox v 23
I tried using the chrome module
var xmlhttp = chrome.Cc["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(chrome.Ci.nsIXMLHttpRequest);
but I got NS_ERROR_FAILURE. I even added the permissions in the package.json
"permissions": {
"cross-domain-content": ["https:[some url]"]
}
But it still gives the same error.
I then used the Request module but didn't work so far. I tried a GET method with the Request module and it works fine. But the POST method always returns a 0 status and an empty response.
I tried doing the same request via a browser http client and it worked fine!! But through the code inside the add-on it always returns a 0.
The request sets headers and of course has a payload.
var contentObject = {[Valid JSON Object]};
var myRequest = Request({
url: "https://[some url]",
headers: {
"pragma": "no-cache"
},
content: contentObject,
contentType: "application/json",
onComplete: function (response) {
console.log("Status: " + response.status);
console.log("Response json: " + JSON.stringify(response));
}
}).post();
Your support is highly appreciated. There are very few resources I found over the internet about this issue and non of them solved my problem.
I guess the server script expects a JSON string representation of the contentObject. But this is not how objects are treated by the request module, they are turned to key/value pairs.
So change
content: contentObject
to
content: JSON.stringify(contentObject)
the POST method always returns a 0 status and an empty response
This might not be direct answer, but I had the same problem last couple of days. A friend who was connected to network via different provider tried the same code and it worked fine. Also, if I remember correctly, I could connect to the port 80 but not to the port where I was sending POST request so that port might be blocked on the network you are connected.

Categories