Access cookie in pre request script in postman v8 - postman

I am trying to get the cookies in the pre request script to chain it with other request which returns as empty array using the example below.
With the latest release of postman v8, the cookies object cannot be fetched using the pm.sendRequest which would otherwise work in postman versions less than 8.
pm.sendRequest(url, function (err, response, { cookies }) {
console.log(cookies.all());
});

I think you might need something like this to see the cookies:
pm.sendRequest("https://postman-echo.com/get", function (err, response, options) {
console.log(options.cookies.members);
});
From here you could loop through the members array to get what you need.

Related

How to read cookies in getStaticProps and getStaticPaths in Next.js

I cannot read cookies in getStaticPaths and getStaticProps, in SSR, I can request the cookie with context but even with packages such as js-cookie, cookie-cutter, cookies, I am unable to read the cookies set, which makes it impossible to get the data.
This is the token I want to get, I removed httpOnly for development.
export async function getStaticPaths(){
const data = await callApi("/jobs", "GET", token)
const paths = data.map(jobs => ({
params: {slug: jobs.slug}
}))
return{
paths,
fallback: true,
}
}
This is the getStaticPaths.
both getStaticPaths and getStaticProps are methods that run on the server (node.js), therefore cookies which is a browser API are not available yet
Cookies can be accessed both on the server req.cookies or req.headers.cookie and on the client document.cookie. But unlike getServerSideProps where the HTML is generated at runtime, getStaticProps generates the HTML at build time and therefore has no know knowledge of requesting devise/browser. This is evident from how user-agent looks when the request is sent from getStaticProps:
'user-agent': 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'
Also, there's a demo app here showing how this all works.
If your reason for trying to access cookies from getStaticProps is for authentication, have a look at this post on The way they built the zeit.co/vercel dashboard (fully static)
Also here, using next-redux-wrapper to access state from getStaticProps.
if you have placed your cookies and want to read them you can get them in getServerSideProps ctx.req.cookies here your cookies
here is the link so you shouldn't try getting cookies in getStaticProps
https://github.com/vercel/next.js/discussions/11734#discussioncomment-3993

Not able to parse Authorization Header

am calling an API with he query paramter as told by my Remedy team and i get the "Not able to parse Authorization Header" error
var yhttp = new XMLHttpRequest();
var phonedata=":People?q=%27Phone%20Number%20Business%27%20%3D%20%22%2B12017148030%22&fields=userid";
yhttp.open('GET', 'https://remproditsm.broadridge.net/api/arsys/v1/entry/CTM:People?q=%27Phone%20Number%20Business%27%20%3D%20%22%2B12017148030%22&fields=ciscofinesse');
yhttp.setRequestHeader('Authorization', 'Bearer' + response);
yhttp.setRequestHeader('Content-Type', 'application/json');
yhttp.send();
have tried AR-JWT instead of Bearer, have tried with application/json header and without, i was not convinced if i should be passing that in the header but remedy team advised me to pass it. Also, this works fine in Postman.
I propose to double check the postman and on the right side you have the CODE button,
then export working version from postman to JavaScript-XHR.
ok i found the issue, AJAx request by default is asynchronous, am using the varibale from the response as the token, and by the time it reaches the 2nd GET API request , it has nothing in the res variable, so i converted my first API request for token to synchronous
xhttp.open('POST', 'url',false);
xhttp.setRequestHeader('authString', 'authentication string');
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.send(data);
res= xhttp.responseText;
document.write(res);
Yes, you need "AR-JWT {token}" as your Authorization header value. The token should be stored after the login call and used for each subsequent REST operation.
https://docs.bmc.com/docs/ars2008/examples-of-using-the-rest-api-to-get-update-and-delete-an-entry-from-a-form-929631054.html

Clearing Cookies Programmatically is not working in Postman and Newman

I need to be able to delete cookies automatically in between requests when they I run my collection of requests in Newman and Postman Runner (mainly Newman).
I followed the suggestion given in this comment by a person from Postman: https://github.com/postmanlabs/postman-app-support/issues/3312#issuecomment-516965288.
But it is not working.
The answer to these two SO questions also tell the same way to go about doing this: Postman: How do you delete cookies in the pre-request script?
Deleting cookies in postman programmatically
Here is the code that I use that the sources above suggest to place in the pre-request script:
const jar = pm.cookies.jar();
jar.clear(pm.request.url, function (error) {
console.log("Error: ");
console.log(error);
//handle error
});
[Note: error is logged as null when I run this code]
I have tried this code many times and also many different modifications of that code. I do white-list the domain too. But I always get the wrong response in the request. When I clear the cookies manually (using the cookie Manager UI dialogue box), the request gives the right response. I need help in determining where the problem could be for me in deleting cookies programmatically.
I also tried this to see what the cookies that I am deleting are:
jar.getAll(pm.request.url, function (error, cookies) {
console.log("Cookies:");
console.log(cookies);
console.log("Error: ");
console.log(error);
});
Here cookies is an empty array. Perhaps that is the problem. But that is very weird since when I check Cookie Manager manually, there are many cookies shown. And once I delete the cookies manually the requests return the right responses.
Another question I had was: What is the purpose of the callback functions that take 'cookies' and 'error' as arguments in the code above. Are these functions called everytime or only under certain conditions? Could not find the purpose of the callback functions in the postman documentation: https://learning.postman.com/docs/postman/sending-api-requests/cookies/
Thank you
If the cookie has "httpOnly" or "secure" header, you can't delete them via script in postman. jar.clear clears all the cookies except these httpOnly and secure ones.
I think this is a bug and needs to be fixed by Postman. If this is intended, there should be a setting in Postman to activate or disable it.

How do you add JSON data to an HTML AWS lambda response body?

I've run into some trouble with a site I am building. It used AWS lambda functions. I am building and deploying on AWS CodeStar.
The site strips the URL parameter (e.g. /BTC), sends that to external API endpoint, which returns some JSON data. I can display the entire JSON response using body: JSON.stringify(response), so it is definitely coming through from the API. However, I would like to the JSON values to HTML markup before sending back to the client. Yet, when I do something like var html = '<h1>JSON.stringify(response['DISPLAY']['BTC']['USD']['MARKET'])</h1>';. I receive an Internal Server Error - Malformed Request.
I can't figure this out. I'm fairly new to the world of AWS, so may be overlooking something, I've looked around in the docs and can't seem to find anything related to this.
Also, when I had the JSON.stringify output displaying on the webpage. If I re-parsed this in the browser console, response['DISPLAY']['BTC']['USD']['MARKET'] returned a value - so I am fairly sure the syntax for the payload data is correct.
exports.get = function(event, context) {
var ticker = event.pathParameters.currency;
rp(`https://min-api.cryptocompare.com/data/pricemultifull?fsyms=${ticker}&tsyms=USD`)
.then(function (response) {
var html = `<h1>${JSON.stringify(response['DISPLAY']['BTC']['USD']['MARKET'])}</h1>`;
context.succeed({
statusCode: 200,
body: html,
headers: {'Content-Type': 'text/html'}
});
})
.catch(function (err) {
console.log('error: ', err);
});
};
Any help would be appreciated! Happy to provide more info if required.
This is caused by a combination of a couple of things, as far as I can tell:
Within your .catch block you are not calling context.error. In other words, if there's an error in your lambda function, the lambda function never signals that it's finished executing properly to the invoker. API gateway throws up its hands in despair and spits out a 502 error.
response is a string, so when you try to access its properties, you cause an exception and end up in your .catch block. First you need to JSON.parse(response)
Here's a helpful note: whenever you call console.log, the log output can be found in CloudWatch > Logs > /aws/lambda/<your-lambda-name>. This can be useful for figuring out why/where things are breaking.

Postman: How do you delete cookies in the pre-request script?

All the postman cookie-management answers I've seen refer to either the browser extension (open chrome, delete cookies viz interceptor etc) or with the app, using the UI to manually manage cookies.
I would like to delete certain cookies in my pre-request code as part of scripting my API tests. (delete them programmatically)
The Sandobx API docs mention pm.cookies so I tried
if (pm.cookies !== null) {
console.log("cookies!");
console.log(pm.cookies);
}
But the pm.cookies array is empty. Yet in the console, the GET call then passes a cookie.
There's also postman.getResponseCookies, which is null (I assume because we're in the pre-request section, not in the test section)
One answer suggested calling the postman-echo service to delete the cookie. I haven't investigated this yet, but it doesn't feel right.
new version now supports that since 2019/08, see more examples here: Delete cookies programmatically · Issue #3312 · postmanlabs/postman-app-support
Prerequisite
Cookie domains to be given programatic access must be whitelisted.
clear all cookies
const jar = pm.cookies.jar();
jar.clear(pm.request.url, function (error) {
// error - <Error>
});
get all cookies
const jar = pm.cookies.jar();
jar.getAll('http://example.com', function (error, cookies) {
// error - <Error>
// cookies - <PostmanCookieList>
// PostmanCookieList: https://www.postmanlabs.com/postman-collection/CookieList.html
});
get specific cookie
const jar = pm.cookies.jar();
jar.get('http://example.com', 'token', function (error, value) {
// error - <Error>
// value - <String>
});
According to the documentation pm API reference the pm.cookie API is only for the Tests tab, not for the Pre-request Script.
The following items are available in TEST SCRIPTS only.
pm.cookies
...
It seems that you will have to stick with this method : Interceptor Blog post
I know this is a very late answer, but for my case where I didn't want to use the cookies to start the execution of the collection, I just needed to uncheck the option "Save cookies after the collection run" and check the option "Run collection without using stored cookies" on the Runner panel.
And then if I want to manage the cookies on my own, I created a first request on the collection and used the Tests tab just to collect the cookies that I wanted and saved them on a variable.
pm.environment.set('cookie', pm.cookies.get('csrftoken'))
pm.environment.set('sessionid', pm.cookies.get('sessionid'))