Postman : Prevent default behaviour on send request - javascript

Description
So, I have a Pre-request script in Postman which runs and gets a API_token, which in turn sets the env variable "api_token". I have set this "api_token" using the script specified in the next section.
Requirement
I want the behaviour to be such.
I click the send button.
The Pre-Request script handles whole request and the default behaviour is prevented.
The result of the request is outputted as if the default request was sent. ( optional. brownie points if you can get this :D )
I tried the following script :
// setting the header body
const options = {
url: 'https://api/v1/login',
method: 'POST',
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: {
mode: 'raw',
urlencoded : [
{ key: 'username', value: 'admin'},
{ key: 'password', value: 'Admin#123'},
]
}
};
// sending the request :D
pm.sendRequest(options, function (err, response) {
pm.environment.set("api_token", response["id"]);
});
// throw new Error("Error : access denied"); I Tried to prevent any further execution;
return;
Shortcomings
Although, It does set the env variable, but it also sends the default request which in turn creates 2 api_tokens for me ( which I want to prevent)
It does not display the response I generated with my pre-request script.

Related

How to get the request body raw inside test cases in TESTS scripts POSTMAN?

I am trying to get the request body raw inside test cases in TESTS scripts?
Here the script in TESTS:
pm.sendRequest({
url: pm.collectionVariables.get("url") + '/xxxxx/' + api + '/xxxxxxxxxxx',
method: 'POST',
header: {
'content-type': 'application/json',
'application': pm.collectionVariables.get("sha256"),
'sign': pm.collectionVariables.get("sign")
},
body: {
mode: 'raw',
raw: JSON.stringify({
deviceId: null,
email: null
})
}
}, console.log(“Request Body: ”, JSON.parse(pm.request.body.raw)),
function(err, res) {
pm.test(“N: All Parameter Null”, function() {
pm.expect(res).to.have.property(‘code’, 200);
pm.expect(res.json()).to.have.property(‘status’, ‘00’);
pm.expect(res.json()).to.have.property(‘message’, ‘Success’);
console.info("All Parameter Null Response Time: " + res.responseTime)
});
})
I’m using console.log(“Request Body :”, JSON.parse(pm.request.body.raw)) to get request body raw, but the content i got is the raw data from BODY (Main Test Cases)
the purpose of this question is to create a signature in the header, based on request body raw that generated with secret key
i have no problem to create signature in BODY (Main Test Cases), the problem only inside TESTS
How can I get the request body from TESTS ?
or anyone experience how to create signature inside TESTS?

No response from API

I have created an API call in excel to get data from a Wix database.
The call:
Dim http As Object, JSON As Object
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "https://username.wixsite.com/mysite/_functions/Functionname", False
http.setRequestHeader "Authorization", "myauthkey"
http.Send
MsgBox (http.responseText)
The javascript http backend file on Wix:
import { ok, notFound, serverError } from 'wix-http-functions';
import wixData from 'wixdata';
export function get_Wixdata() {
let options = {
"headers": {
"content-type": "application/json"
}
};
return wixData.query("wix data collection name")
.find()
.then(results => {
if (results.items.length > 0) {
options.body ={
"items": results.items
}
return ok(options);
}
})
}
I tested the call (without authorisation) on JSON place holder and it worked fine.
Just trying to debug what's happening as I am getting "" as a response.
Even if I enter the wrong API key I still get "", even a wrong url it's still a "" response.
I take it I am clearly way off the mark with what I am trying to do..
Did you tried put both headers in your request, like the following:
let headers = new Headers({
'Content-Type': 'application/json',
'Authorization': '....'
});
The issue was with the VBA call, the header was not needed.
Dim https As Object, JSON As Object
Set https = CreateObject("MSXML2.XMLHTTP")
With CreateObject("Microsoft.XMLHTTP")
.Open "GET", "end point url", False
.send
response = .responseText
End With

Adding multiple request headers in test script (Postman)

I am running a for loop with multiple requests in order to extract information from our API. The only problem is, I get console errors saying token and client headers are required to view response. I can only add one header in postman though in the test script. Is there something I'm not seeing?
for (k = 0; k < id.length; k++) {
const emailRequest = {
url: "" + id[k] + "/products",
method: "GET",
header: [{
'key': "X-Auth-Token",
"value": "",
}
],
body:{
mode: 'application/json',
raw: JSON.stringify({
client_id: '',
})
}
};
}
The header is not an Array. It is passed as an object with one name-value pair per header. The header should be given as below
header: {
'X-AUTH-TOKEN': 'mytoken',
'Content-Type': 'application/json'
}
Why don't you use multiple headers and variable to achieve this - then you can manipulate variables with scripts as you like.
Image
Useful Links:
https://learning.getpostman.com/docs/postman/environments_and_globals/variables/
I have something which can help you:
my requirements:
key value
"X-Auth-Token" "38432904832904"
"Content-Type" "application/json"
Solution: add this script in Pre-request script
pm.request.headers.add({
key:"X-Auth-Token",
value:"38432904832904"
});
pm.request.headers.add({
key:"Content-Type",
value
})

When sending POST request to backend API via fetch(), the body has only key and no value

When I'm sending a POST request to my backend express server, the req.body contains only the key part where the entire body is the key and the value part is empty
This is the frontend fetch request
let data = {
videoUrl: "dummy text"
}
fetch("/api/getinfo", {
method:"POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
body: JSON.stringify(data)
})
This is how I handle it in backend (NOTE: I'm using body-parser)
app.post("/api/getinfo", (req,res) => {
console.log(req.body);
}
I expect the output to be
'{ "videoUrl":"dummy text" }'
But what I get is
{ '{"videoUrl":"dummy text"}': '' }
The entire requests body is the key, and the value is empty.
What am I doing wrong?
You are using the wrong Content-Type to send json
Try
"Content-Type": "application/json;charset=UTF-8"
I noticed an issue in your header;
fetch("/api/getinfo", {
method:"POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" //this very line
},
I guess what you meant is
fetch("/api/getinfo", {
method:"POST",
headers: {
'Content-type': 'application/json; charset=utf-8'
},
Note: Your header denotes what the content is encoded in. It is not necessarily possible to deduce the type of the content from the content itself, i.e. you can't necessarily just look at the content and know what to do with it. So you need to be sure of what you're writing in your header else you will end up with an error.
I will suggest you get to read more about What does “Content-type: application/json; charset=utf-8” really mean?
The problem is that you are stringifying the data:
body: JSON.stringify(data)
should be
body: data
That should fix it

How to add text to the body of a CasperJS thenOpen() POST request

I need to write a script inside of datorama.com to access pardot.com. Pardot does have an API that requires a request that has a request inside the body as
POST: https://pi.pardot.com/api/login/version/3
message body: email=&password=&user_key=
Right now here is my code:
phantom.casperPath = casperPath;
phantom.injectJs(casperPath + "/bin/bootstrap.js");
var casper = require('casper').create({
verbose: true,
logLevel: 'debug'
});
casper.start().thenOpen('https://pi.pardot.com/api/login/version/3',{
method: 'post',
content: {
'text' : 'email=<myemail>&password=<password>&user_key=<userKey>'
}
}, function(response) {
this.echo(this.getHTML());
});
casper.run();
I can tell that it is getting through to the server because it is responding this.echo(this.getHTML()); "Login Failed" . I am using the right email/password/user_Key because i am pulling that from the API Console for pardot and it is working there.... So I believe the issue is I am not setting the body of the request correctly.
So does anyone know a way to set the body on the request?
casper.open() or casper.thenOpen() don't understand the content setting. You probably wanted to use data:
casper.start()
.thenOpen('https://pi.pardot.com/api/login/version/3', {
method: 'post',
data: 'email=<myemail>&password=<password>&user_key=<userKey>'
}, function() { ... });
Don't forget to use encodeURIComponent() on the email, password and user key parameters if you build the string yourself.
You can also pass an object:
casper.start()
.thenOpen('https://pi.pardot.com/api/login/version/3', {
method: 'post',
data: {
email: '<myemail>',
password: '<password>',
user_key: '<userKey>'
}
}, function() { ... });
If you expect something else than HTML from the API, then you should use casper.getPageContent() instead of casper.getHTML().

Categories

Resources