// Import your JSON file here constfile=require("@users/B02D96D5.default_message_32E64A5B.json");functiononRequest(context, url, request) {// 1. Extract the queryName from the requestvar queryName =request.body.query.match(/\S+/gi)[1].split('(').shift();// 2. Save to sharedStatesharedState.queryName = queryName// Donereturn request;}functiononResponse(context, url, request, response) {// 3. Check if it's the request we need to mapif (sharedState.queryName =="user") {// 4. Import the local file by Action Button -> Import// Get the local JSON file and set it as a body (like Map Local)response.headers["Content-Type"] ="application/json";response.body = file; }// Donereturn response;}
Use ArrayBuffer in Request/Response Body
Since Javascript doesn't have the Data object type, the Data Body will convert to Base64 Encoded String in Javascript. To pass Uint8Array, blob, or ArrayBuffer to the body, make sure you convert to Base64 Encoded String and set the ContentType to application/octet-stream
Proxyman will convert Base64 Encoding to ArrayBuffer, so the client will receive the data properly.
// Importconst { btoa } =require('@addons/Base64.js');functiononResponse(context, url, request, response) {// Construct the ArrayBufferconstbuffer=newArrayBuffer(256)constview=newUint8Array(buffer)for (let i =0; i <view.length; i++) { view[i] = i }// Convert ArrayBuffer to Base64Stringvar newBody =btoa(String.fromCharCode.apply(null,newUint8Array(buffer)));// Set new bodyresponse.body = newBody;response.statusCode =200response.headers['Content-Type'] ='application/octet-stream'// Donereturn response;}
2. More -> Import JSON or Other Files. Then selecting your file
3. Proxyman will add the import code to the top of the script
// ~/Library/Application Support/com.proxyman.NSProxy/users/myfile.jsonconstfile=require("@users/myfile.json");functiononResponse(context, url, request, response) {// 1. Set header to JSON if needresponse.headers["Content-Type"] ="application/json";// 2. Set Body as a imported fileresponse.body = file;return response;}
The selected file is copied to ~/Library/Application\ Support/com.proxyman.NSProxy/users folder.
To support other format files, such as image, text, pdf. Make sure you have correct Header Content-Type
Binary File
Follow the same above instruction (Select your Binary File)
Set it as a body
// ~/Library/Application Support/com.proxyman.NSProxy/users/myscreenshot.pngconstfile=require("@users/myscreenshot.png");functiononResponse(context, url, request, response) {// Set headerresponse.headers["Content-Type"] ="image/png";// Set Bodyresponse.body = file;return response;}
Text-Based File
Follow the same above instruction (Select your Binary File)
Set it as a body
// ~/Library/Application Support/com.proxyman.NSProxy/users/main.cssconstfile=require("@users/main.css");functiononResponse(context, url, request, response) {// Set headerresponse.headers["Content-Type"] ="text/css";// Set Bodyresponse.body = file;return response;}
Import File without using the "Import Tool"
From Proxyman 2.24.0+, you can import any files without using the "Import File".
// Import your file from your Desktop folderconstfile=require("~/Desktop/myfile.json");functiononResponse(context, url, request, response) {// 1. Set header to JSON if needresponse.headers["Content-Type"] ="application/json";// 2. Set Body as a imported fileresponse.body = file;return response;}
If the file has ".js" as an extension => Proxyman will execute it as a JS Script
Otherwise, Proxyman will import it as normal
Only files that are imported by using the "Import Tool", are included when exporting the script to your colleague.
Use as Mock API
You can use Scripting as a Mock API by following this guideline.
const { inflate,deflate } =require("@addons/Pako.js")// Compressvar input ="Hello World from Pako!!!"var result =deflate(input);console.log(result); // eJzzSM3JyVcIzy/KSVFIK8rPVQhIzM5XVFQEAGsMB/8=// Decompressvar text ='eJzzSM3JyVcIzy/KSVFIK8rPVQhIzM5XVFQEAGsMB/8=';var rawText =inflate(text);console.log(rawText); // Hello World from Pako!!!
GZip/UnGZip
const { ungzip,gzip } =require("@addons/Pako.js")// Compressvar text ='HelloWorld';var result =gzip(text);console.log(result); // H4sIAAAAAAAAA/NIzcnJD88vykkBAHkMd3cKAAAA// Decompressvar text ='H4sIAAAAAAAAA/NIzcnJD88vykkBAHkMd3cKAAAA';var rawText =ungzip(text);console.log(rawText); // HelloWorld
JWT Decode
const { jwtDecode } =require('@addons/JWTDecode.js');var text ='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';var jSONObject =jwtDecode(text)
Logging
// Print the objconstmyObj= {};console.log(myObj);// Print type of the objconsole.log(typeof(myObj));
functiononResponse(context, url, request, response) {// Write to single filewriteToFile(response.body,"~/Desktop/body.json");// Write the Body to file with flow IDwriteToFile(response.body,"~/Desktop/sample-"+context.flow.id);// Donereturn response;}
Append Mode (Only for Proxyman 3.6.2+)
asyncfunctiononResponse(context, url, request, response) {// Append to the existed file// Or create a new file if it doesn't existvar opt = {appendFile:true}writeToFile(response.body,"~/Desktop/body.json", opt);// Donereturn response;}
Check if the first exist
Available: Proxyman macOS 5.4.0+
asyncfunctiononRequest(context, url, request) {constfilePath="~/Desktop/myfile.json"// check if the file existsif (isFileExists(filePath)) {console.log("File exists"); } else {console.log("File NOT exists"); }// Donereturn request;}
functiononRequest(context, url, request) {// Replace v1 to v2 in URL Pathvar newPath =request.path.replace("v1","v2");request.path = newPath// Donereturn request;}
Map localhost to production
functiononRequest(context, url, request) {// Use production URLrequest.scheme ="https";request.host ="proxyman.io";request.port =443;// Donereturn request;}
Map production to localhost
functiononRequest(context, url, request) {// Use production URLrequest.scheme ="http";request.host ="localhost";request.port =3000;// Donereturn request;}
Make async/await HTTP Request (macOS)
This feature `$http` is available on the macOS version. To use on Windows, please check the next part.
GET Request with Query
asyncfunctiononResponse(context, url, request, response) { // GET Request with Queryvar url ="https://httpbin.proxyman.app/get?id=proxyman&country=united%20states";var output =await$http.get(url);// Get Status Codeconsole.log(output.statusCode);// Get bodyconsole.log(output.body)// Get headerconsole.log(output.headers)// Donereturn response;}
POST Request with JSON Body
asyncfunctiononResponse(context, url, request, response) { // Define JSON Body and Header// Make sure "Content-Type" is "application/json"var param = { body: {"user": {"name":"Proxyman" } }, headers: {"Content-Type":"application/json" } }// POST request with awaitvar output =await$http.post("https://httpbin.proxyman.app/post", param);// Get Status Codeconsole.log(output.statusCode);// Get bodyconsole.log(output.body)// Get headerconsole.log(output.headers)// Donereturn response;}
POST Request with application/x-www-form-urlencoded body
asyncfunctiononResponse(context, url, request, response) { // Define form Body and Header// Make sure "Content-Type" is "application/x-www-form-urlencoded"var param = { body: {"key1":"value1","key2":"value2" }, headers: {"Content-Type":"application/x-www-form-urlencoded" } }// POST request with awaitvar output =await$http.post("https://httpbin.proxyman.app/post", param);// Get Status Codeconsole.log(output.statusCode);// Get bodyconsole.log(output.body)// Get headerconsole.log(output.headers)// Donereturn response;}
PUT / PATCH / DELETE Request
asyncfunctiononRequest(context, url, request) { var param = { body: {"user": {"name":"Proxyman" } }, headers: {"Content-Type":"application/json" } var output =await$http.post("https://httpbin.proxyman.app/post", param); var output =await$http.put("https://httpbin.proxyman.app/put", param); var output =await$http.delete("https://httpbin.proxyman.app/delete", param);// Done return request;}
Make async/await HTTP Request (Windows/Linux)
Windows/Linux ships with a built-in Axios library. You can easily make HTTP(s) requests with `Axios` syntax.
functiononRequest(context, url, request) {// drop the connectionabort();}
functiononRequest(context, url, request) {// Use the if to abort on certain conditionsif (true) {abort();return; // Must return a void to stop the func }// Donereturn request;}
Abort the response
functiononResponse(context, url, request, response) { // drop the connectionabort();}
URL and URLSearchParams
From Proxyman 4.13.0 or later, URL and URLSearchParams are natively supported.
Make sure we enable the permission first, in the More Button -> Environment Variables -> Allow all scripts to read env.
asyncfunctiononRequest(context, url, request) {// manually reload to get the latest changes_reloadEnv();// get envconsole.log($PROXYMAN_ID)// Donereturn request;}