Skip to content

Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia

merge and fix

breno-pereiradb0826d43aca
diff --cc pages/index.vue
index 0ed4658d4,eca37a923..e62ca8e19
--- a/pages/index.vue
+++ b/pages/index.vue
@@@ -42,7 -43,7 +43,7 @@@
<ul>
<li>
<label for="method">Method</label>
-- <select id="method" v-model="method">
++ <select id="method" v-model="method" @change="methodChange">
<option>GET</option>
<option>HEAD</option>
<option>POST</option>
@@@ -97,24 -130,22 +130,24 @@@
</ul>
<ul v-for="(param, index) in bodyParams" :key="index">
<li>
- <input
- :placeholder="'key '+(index+1)"
- :name="'bparam'+index"
- v-model="param.key"
- @keyup.prevent="setRouteQueryState"
+ <input
+ :placeholder="'key '+(index+1)"
+ :name="'bparam'+index"
+ :value="param.key"
+ @change="$store.commit('setKeyBodyParams', { index, value: $event.target.value })"
+ @keyup.prevent="setRouteQueryState"
autofocus
- >
+ />
</li>
<li>
- <input
- :placeholder="'value '+(index+1)"
- :id="'bvalue'+index"
- :name="'bvalue'+index"
- v-model="param.value"
+ <input
+ :placeholder="'value '+(index+1)"
+ :id="'bvalue'+index"
+ :name="'bvalue'+index"
+ :value="param.value"
+ @change="$store.commit('setValueBodyParams', { index, value: $event.target.value })"
@keyup.prevent="setRouteQueryState"
- >
+ />
</li>
<div>
<li>
@@@ -295,23 -351,21 +353,23 @@@
</ul>
<ul v-for="(header, index) in headers" :key="index">
<li>
- <input
- :placeholder="'header '+(index+1)"
- :name="'header'+index"
- v-model="header.key"
- @keyup.prevent="setRouteQueryState"
+ <input
+ :placeholder="'header '+(index+1)"
+ :name="'header'+index"
+ :value="header.key"
+ @change="$store.commit('setKeyHeader', { index, value: $event.target.value })"
+ @keyup.prevent="setRouteQueryState"
autofocus
- >
+ />
</li>
<li>
- <input
- :placeholder="'value '+(index+1)"
- :name="'value'+index"
- v-model="header.value"
+ <input
+ :placeholder="'value '+(index+1)"
+ :name="'value'+index"
+ :value="header.value"
+ @change="$store.commit('setValueHeader', { index, value: $event.target.value })"
@keyup.prevent="setRouteQueryState"
- >
+ />
</li>
<div>
<li>
@@@ -351,21 -412,15 +416,21 @@@
</ul>
<ul v-for="(param, index) in params" :key="index">
<li>
- <input
- :placeholder="'parameter '+(index+1)"
- :name="'param'+index"
- v-model="param.key"
+ <input
+ :placeholder="'parameter '+(index+1)"
+ :name="'param'+index"
+ :value="param.key"
+ @change="$store.commit('setKeyParams', { index, value: $event.target.value })"
autofocus
- >
+ />
</li>
<li>
- <input :placeholder="'value '+(index+1)" :name="'value'+index" v-model="param.value" />
+ <input
+ :placeholder="'value '+(index+1)"
+ :name="'value'+index"
+ :value="param.value"
+ @change="$store.commit('setValueParams', { index, value: $event.target.value })"
- >
++ />
</li>
<div>
<li>
@@@ -393,880 -513,997 +523,1030 @@@
</div>
</template>
<script>
- import url from 'url';
- import querystring from "querystring";
- import autocomplete from '../components/autocomplete';
- import history from "../components/history";
- import section from "../components/section";
- import textareaAutoHeight from "../directives/textareaAutoHeight";
- import toggle from "../components/toggle";
- import modal from "../components/modal";
- import collections from '../components/collections';
- import saveRequestAs from '../components/collections/saveRequestAs';
- import parseCurlCommand from '../assets/js/curlparser.js';
- import hljs from 'highlight.js';
- import 'highlight.js/styles/dracula.css';
+ import url from "url";
+ import querystring from "querystring";
+ import autocomplete from "../components/autocomplete";
+ import history from "../components/history";
+ import section from "../components/section";
+ import textareaAutoHeight from "../directives/textareaAutoHeight";
+ import toggle from "../components/toggle";
+ import modal from "../components/modal";
+ import collections from "../components/collections";
+ import saveRequestAs from "../components/collections/saveRequestAs";
+ import parseCurlCommand from "../assets/js/curlparser.js";
+ import hljs from "highlight.js";
+ import "highlight.js/styles/dracula.css";
- const statusCategories = [{
- name: 'informational',
- statusCodeRegex: new RegExp(/[1][0-9]+/),
- className: 'info-response'
- },
- {
- name: 'successful',
- statusCodeRegex: new RegExp(/[2][0-9]+/),
- className: 'success-response'
- },
- {
- name: 'redirection',
- statusCodeRegex: new RegExp(/[3][0-9]+/),
- className: 'redir-response'
- },
- {
- name: 'client error',
- statusCodeRegex: new RegExp(/[4][0-9]+/),
- className: 'cl-error-response'
- },
- {
- name: 'server error',
- statusCodeRegex: new RegExp(/[5][0-9]+/),
- className: 'sv-error-response'
- },
- {
- // this object is a catch-all for when no other objects match and should always be last
- name: 'unknown',
- statusCodeRegex: new RegExp(/.*/),
- className: 'missing-data-response'
- }
- ];
- const parseHeaders = xhr => {
- const headers = xhr.getAllResponseHeaders().trim().split(/[\r\n]+/);
- const headerMap = {};
- headers.forEach(line => {
- const parts = line.split(': ');
- const header = parts.shift().toLowerCase();
- const value = parts.join(': ');
- headerMap[header] = value
- });
- return headerMap
+ const statusCategories = [
+ {
+ name: "informational",
+ statusCodeRegex: new RegExp(/[1][0-9]+/),
+ className: "info-response"
+ },
+ {
+ name: "successful",
+ statusCodeRegex: new RegExp(/[2][0-9]+/),
+ className: "success-response"
+ },
+ {
+ name: "redirection",
+ statusCodeRegex: new RegExp(/[3][0-9]+/),
+ className: "redir-response"
+ },
+ {
+ name: "client error",
+ statusCodeRegex: new RegExp(/[4][0-9]+/),
+ className: "cl-error-response"
+ },
+ {
+ name: "server error",
+ statusCodeRegex: new RegExp(/[5][0-9]+/),
+ className: "sv-error-response"
+ },
+ {
+ // this object is a catch-all for when no other objects match and should always be last
+ name: "unknown",
+ statusCodeRegex: new RegExp(/.*/),
+ className: "missing-data-response"
+ }
+ ];
+ const parseHeaders = xhr => {
+ const headers = xhr
+ .getAllResponseHeaders()
+ .trim()
+ .split(/[\r\n]+/);
+ const headerMap = {};
+ headers.forEach(line => {
+ const parts = line.split(": ");
+ const header = parts.shift().toLowerCase();
+ const value = parts.join(": ");
+ headerMap[header] = value;
+ });
+ return headerMap;
+ };
+ export const findStatusGroup = responseStatus =>
+ statusCategories.find(status => status.statusCodeRegex.test(responseStatus));
- };
- export const findStatusGroup = responseStatus => statusCategories.find(status => status.statusCodeRegex.test(
- responseStatus));
+ export default {
+ directives: {
+ textareaAutoHeight
+ },
- export default {
- directives: {
- textareaAutoHeight
- },
+ components: {
+ "pw-section": section,
+ "pw-toggle": toggle,
+ "pw-modal": modal,
+ history,
+ autocomplete,
+ collections,
+ saveRequestAs
+ },
+ data () {
+ return {
- label: "",
+ showModal: false,
+ copyButton: '<i class="material-icons">file_copy</i>',
+ copiedButton: '<i class="material-icons">done</i>',
- method: "GET",
- url: "https://reqres.in",
- auth: "None",
- path: "/api/users",
- httpUser: "",
- httpPassword: "",
- passwordFieldType: "password",
- bearerToken: "",
- headers: [],
- params: [],
- bodyParams: [],
- rawParams: "",
- rawInput: false,
- contentType: "application/json",
- requestType: "JavaScript XHR",
+ isHidden: true,
+ response: {
+ status: "",
+ headers: "",
+ body: ""
+ },
+ previewEnabled: false,
+ paramsWatchEnabled: true,
- components: {
- 'pw-section': section,
- 'pw-toggle': toggle,
- 'pw-modal': modal,
- history,
- autocomplete,
- collections,
- saveRequestAs,
- },
- data() {
- return {
- showModal: false,
- copyButton: '<i class="material-icons">file_copy</i>',
- copiedButton: '<i class="material-icons">done</i>',
- isHidden: true,
- response: {
- status: '',
- headers: '',
- body: ''
- },
- previewEnabled: false,
- paramsWatchEnabled: true,
+ /**
+ * These are content types that can be automatically
+ * serialized by postwoman.
+ */
+ knownContentTypes: [
+ "application/json",
+ "application/x-www-form-urlencoded"
+ ],
- /**
- * These are content types that can be automatically
- * serialized by postwoman.
- */
- knownContentTypes: [
- 'application/json',
- 'application/x-www-form-urlencoded'
- ],
+ /**
+ * These are a list of Content Types known to Postwoman.
+ */
+ validContentTypes: [
+ "application/json",
+ "application/hal+json",
+ "application/xml",
+ "application/x-www-form-urlencoded",
+ "text/html",
+ "text/plain"
+ ],
+ showRequestModal: false,
+ editRequest: {},
- /**
- * These are a list of Content Types known to Postwoman.
- */
- validContentTypes: [
- 'application/json',
- 'application/hal+json',
- 'application/xml',
- 'application/x-www-form-urlencoded',
- 'text/html',
- 'text/plain'
- ],
- showRequestModal: false,
- editRequest: {},
+ urlExcludes: {}
+ };
+ },
+ watch: {
+ urlExcludes: {
+ deep: true,
+ handler () {
+ this.$store.commit("postwoman/applySetting", ['URL_EXCLUDES', Object.assign({}, this.urlExcludes)]);
+ }
+ },
+ contentType(val) {
+ this.rawInput = !this.knownContentTypes.includes(val);
+ },
+ rawInput(status) {
+ if (status && this.rawParams === "") this.rawParams = "{}";
+ else this.setRouteQueryState();
+ },
+ "response.body": function(val) {
+ var responseText =
+ document.querySelector("div#response-details-wrapper pre code") != null
+ ? document.querySelector("div#response-details-wrapper pre code")
+ : null;
+ if (responseText) {
+ if (
+ document.querySelector(".hljs") !== null &&
+ responseText.innerHTML.indexOf('<span class="hljs') !== -1
+ ) {
+ responseText.removeAttribute("class");
+ responseText.innerHTML = null;
+ responseText.innerText = this.response.body;
+ } else if (
+ responseText &&
+ this.response.body !== "(waiting to send request)" &&
+ this.response.body !== "Loading..." &&
+ this.response.body !== "See JavaScript console (F12) for details."
+ ) {
+ responseText.innerText =
+ this.responseType === "application/json" ||
+ this.responseType === "application/hal+json"
+ ? JSON.stringify(this.response.body, null, 2)
+ : this.response.body;
+ hljs.highlightBlock(
+ document.querySelector("div#response-details-wrapper pre code")
+ );
+ } else {
+ responseText.innerText = this.response.body;
+ }
}
},
- watch: {
- contentType(val) {
- this.rawInput = !this.knownContentTypes.includes(val);
- },
- rawInput(status) {
- if (status && this.rawParams === '') this.rawParams = '{}'
- else this.setRouteQueryState()
- },
- 'response.body': function (val) {
- var responseText = document.querySelector("div#response-details-wrapper pre code") != null ? document
- .querySelector("div#response-details-wrapper pre code") : null;
- if (responseText) {
- if (document.querySelector('.hljs') !== null && responseText.innerHTML.indexOf('<span class="hljs') !== -
- 1) {
- responseText.removeAttribute("class");
- responseText.innerHTML = null;
- responseText.innerText = this.response.body;
- } else if (responseText && this.response.body !== "(waiting to send request)" && this.response.body !==
- "Loading..." && this.response.body !== "See JavaScript console (F12) for details.") {
- responseText.innerText = this.responseType === 'application/json' || this.responseType === 'application/hal+json' ? JSON.stringify(this.response.body,
- null, 2) : this.response.body;
- hljs.highlightBlock(document.querySelector("div#response-details-wrapper pre code"));
- } else {
- responseText.innerText = this.response.body
- }
+ params: {
+ handler: function(newValue) {
+ if (!this.paramsWatchEnabled) {
+ this.paramsWatchEnabled = true;
+ return;
+ }
+ let path = this.path;
+ let queryString = newValue
+ .filter(({ key }) => !!key)
+ .map(({ key, value }) => `${key}=${value}`)
+ .join("&");
+ queryString = queryString === "" ? "" : `?${queryString}`;
+ if (path.includes("?")) {
+ path = path.slice(0, path.indexOf("?")) + queryString;
+ } else {
+ path = path + queryString;
}
- },
- params: {
- handler: function(newValue) {
- if(!this.paramsWatchEnabled) {
- this.paramsWatchEnabled = true;
- return;
- }
- let path = this.path;
- let queryString = newValue
- .filter(({
- key
- }) => !!key)
- .map(({
- key,
- value
- }) => `${key}=${value}`).join('&')
- queryString = queryString === '' ? '' : `?${queryString}`
- if(path.includes('?')) {
- path = path.slice(0, path.indexOf('?')) + queryString;
- } else {
- path = path + queryString
- }
- this.path = path;
- },
- deep: true
- },
- selectedRequest (newValue, oldValue) {
- // @TODO: Convert all variables to single request variable
- if (!newValue) return;
- this.url = newValue.url;
- this.path = newValue.path;
- this.method = newValue.method;
- this.auth = newValue.auth;
- this.httpUser = newValue.httpUser;
- this.httpPassword = newValue.httpPassword;
- this.passwordFieldType = newValue.passwordFieldType;
- this.bearerToken = newValue.bearerToken;
- this.headers = newValue.headers;
- this.params = newValue.params;
- this.bodyParams = newValue.bodyParams;
- this.rawParams = newValue.rawParams;
- this.rawInput = newValue.rawInput;
- this.contentType = newValue.contentType;
- this.requestType = newValue.requestType;
+ this.path = path;
},
- editingRequest (newValue) {
- this.editRequest = newValue;
- this.showRequestModal = true;
- }
+ deep: true
+ },
+ selectedRequest(newValue, oldValue) {
+ // @TODO: Convert all variables to single request variable
+ if (!newValue) return;
+ this.url = newValue.url;
+ this.path = newValue.path;
+ this.method = newValue.method;
+ this.auth = newValue.auth;
+ this.httpUser = newValue.httpUser;
+ this.httpPassword = newValue.httpPassword;
+ this.passwordFieldType = newValue.passwordFieldType;
+ this.bearerToken = newValue.bearerToken;
+ this.headers = newValue.headers;
+ this.params = newValue.params;
+ this.bodyParams = newValue.bodyParams;
+ this.rawParams = newValue.rawParams;
+ this.rawInput = newValue.rawInput;
+ this.contentType = newValue.contentType;
+ this.requestType = newValue.requestType;
},
- computed: {
- url: {
+ editingRequest(newValue) {
+ this.editRequest = newValue;
+ this.showRequestModal = true;
+ }
+ },
+ computed: {
++ url: {
+ get() { return this.$store.state.request.url; },
+ set(value) { this.$store.commit('setState', { value, 'attribute': 'url' }) },
+ },
- method: {
- get() { return this.$store.state.request.method; },
- set(value) { this.$store.commit('setState', { value, 'attribute': 'method' }) },
- },
- path: {
- get() { return this.$store.state.request.path; },
- set(value) { this.$store.commit('setState', { value, 'attribute': 'path' }) },
- },
- label: {
- get() { return this.$store.state.request.label; },
- set(value) { this.$store.commit('setState', { value, 'attribute': 'label' }) },
- },
- auth: {
- get() { return this.$store.state.request.auth; },
- set(value) { this.$store.commit('setState', { value, 'attribute': 'auth' }) },
- },
- httpUser: {
- get() { return this.$store.state.request.httpUser; },
- set(value) { this.$store.commit('setState', { value, 'attribute': 'httpUser' }) },
- },
- httpPassword: {
- get() { return this.$store.state.request.httpPassword; },
- set(value) { this.$store.commit('setState', { value, 'attribute': 'httpPassword' }) },
- },
- bearerToken: {
- get() { return this.$store.state.request.bearerToken; },
- set(value) { this.$store.commit('setState', { value, 'attribute': 'bearerToken' }) },
- },
- headers: {
- get() { return this.$store.state.request.headers; },
- set(value) { this.$store.commit('setState', { value, 'attribute': 'headers' }) },
- },
- params: {
- get() { return this.$store.state.request.params; },
- set(value) { this.$store.commit('setState', { value, 'attribute': 'params' }) },
- },
- bodyParams: {
- get() { return this.$store.state.request.bodyParams; },
- set(value) { this.$store.commit('setState', { value, 'attribute': 'bodyParams' }) },
- },
- rawParams: {
- get() { return this.$store.state.request.rawParams; },
- set(value) { this.$store.commit('setState', { value, 'attribute': 'rawParams' }) },
- },
- rawInput: {
- get() { return this.$store.state.request.rawInput; },
- set(value) { this.$store.commit('setState', { value, 'attribute': 'rawInput' }) },
- },
- requestType: {
- get() { return this.$store.state.request.requestType; },
- set(value) { this.$store.commit('setState', { value, 'attribute': 'requestType' }) },
- },
- contentType: {
- get() { return this.$store.state.request.contentType; },
- set(value) { this.$store.commit('setState', { value, 'attribute': 'contentType' }) },
- },
- passwordFieldType: {
- get() { return this.$store.state.request.passwordFieldType; },
- set(value) { this.$store.commit('setState', { value, 'attribute': 'passwordFieldType' }) }
- },
- selectedRequest() {
- return this.$store.state.postwoman.selectedRequest;
- },
- editingRequest() {
- return this.$store.state.postwoman.editingRequest;
- },
- requestName() {
- return this.label
- },
- statusCategory() {
- return findStatusGroup(this.response.status);
- },
- isValidURL() {
- const protocol = '^(https?:\\/\\/)?';
- const validIP = new RegExp(protocol +
- "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
- const validHostname = new RegExp(protocol +
- "(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$"
- );
- return validIP.test(this.url) || validHostname.test(this.url);
- },
- hasRequestBody() {
- return ['POST', 'PUT', 'PATCH'].includes(this.method);
- },
- pathName() {
- return this.path.match(/^([^?]*)\??/)[1]
- },
- rawRequestBody() {
- const {
- bodyParams
- } = this
- if (this.contentType === 'application/json') {
- try {
- const obj = JSON.parse(`{${bodyParams.filter(({key}) => !!key).map(({key, value}) => `
++ method: {
++ get() { return this.$store.state.request.method; },
++ set(value) { this.$store.commit('setState', { value, 'attribute': 'method' }) },
++ },
++ path: {
++ get() { return this.$store.state.request.path; },
++ set(value) { this.$store.commit('setState', { value, 'attribute': 'path' }) },
++ },
++ label: {
++ get() { return this.$store.state.request.label; },
++ set(value) { this.$store.commit('setState', { value, 'attribute': 'label' }) },
++ },
++ auth: {
++ get() { return this.$store.state.request.auth; },
++ set(value) { this.$store.commit('setState', { value, 'attribute': 'auth' }) },
++ },
++ httpUser: {
++ get() { return this.$store.state.request.httpUser; },
++ set(value) { this.$store.commit('setState', { value, 'attribute': 'httpUser' }) },
++ },
++ httpPassword: {
++ get() { return this.$store.state.request.httpPassword; },
++ set(value) { this.$store.commit('setState', { value, 'attribute': 'httpPassword' }) },
++ },
++ bearerToken: {
++ get() { return this.$store.state.request.bearerToken; },
++ set(value) { this.$store.commit('setState', { value, 'attribute': 'bearerToken' }) },
++ },
++ headers: {
++ get() { return this.$store.state.request.headers; },
++ set(value) { this.$store.commit('setState', { value, 'attribute': 'headers' }) },
++ },
++ params: {
++ get() { return this.$store.state.request.params; },
++ set(value) { this.$store.commit('setState', { value, 'attribute': 'params' }) },
++ },
++ bodyParams: {
++ get() { return this.$store.state.request.bodyParams; },
++ set(value) { this.$store.commit('setState', { value, 'attribute': 'bodyParams' }) },
++ },
++ rawParams: {
++ get() { return this.$store.state.request.rawParams; },
++ set(value) { this.$store.commit('setState', { value, 'attribute': 'rawParams' }) },
++ },
++ rawInput: {
++ get() { return this.$store.state.request.rawInput; },
++ set(value) { this.$store.commit('setState', { value, 'attribute': 'rawInput' }) },
++ },
++ requestType: {
++ get() { return this.$store.state.request.requestType; },
++ set(value) { this.$store.commit('setState', { value, 'attribute': 'requestType' }) },
++ },
++ contentType: {
++ get() { return this.$store.state.request.contentType; },
++ set(value) { this.$store.commit('setState', { value, 'attribute': 'contentType' }) },
++ },
++ passwordFieldType: {
++ get() { return this.$store.state.request.passwordFieldType; },
++ set(value) { this.$store.commit('setState', { value, 'attribute': 'passwordFieldType' }) }
++ },
++
+ selectedRequest() {
+ return this.$store.state.postwoman.selectedRequest;
+ },
+ editingRequest() {
+ return this.$store.state.postwoman.editingRequest;
+ },
+ requestName() {
+ return this.label;
+ },
+ statusCategory() {
+ return findStatusGroup(this.response.status);
+ },
+ isValidURL() {
+ const protocol = "^(https?:\\/\\/)?";
+ const validIP = new RegExp(
+ protocol +
+ "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
+ );
+ const validHostname = new RegExp(
+ protocol +
+ "(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]).)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$"
+ );
+ return validIP.test(this.url) || validHostname.test(this.url);
+ },
+ hasRequestBody() {
+ return ["POST", "PUT", "PATCH"].includes(this.method);
+ },
+ pathName() {
+ return this.path.match(/^([^?]*)\??/)[1];
+ },
+ rawRequestBody() {
+ const { bodyParams } = this;
+ if (this.contentType === "application/json") {
+ try {
+ const obj = JSON.parse(
+ `{${bodyParams
+ .filter(({ key }) => !!key)
+ .map(
+ ({ key, value }) => `
"${key}": "${value}"
- `).join()}}`)
- return JSON.stringify(obj)
- } catch (ex) {
- return 'invalid'
- }
+ `
+ )
+ .join()}}`
+ );
+ return JSON.stringify(obj);
+ } catch (ex) {
+ return "invalid";
+ }
+ } else {
+ return bodyParams
+ .filter(({ key }) => !!key)
+ .map(({ key, value }) => `${key}=${encodeURIComponent(value)}`)
+ .join("&");
+ }
+ },
+ headerString() {
+ const result = this.headers
+ .filter(({ key }) => !!key)
+ .map(({ key, value }) => `${key}: ${value}`)
+ .join(",\n");
+ return result === "" ? "" : `${result}`;
+ },
+ queryString() {
+ const result = this.params
+ .filter(({ key }) => !!key)
+ .map(({ key, value }) => `${key}=${encodeURIComponent(value)}`)
+ .join("&");
+ return result === "" ? "" : `?${result}`;
+ },
+ responseType() {
+ return (this.response.headers["content-type"] || "")
+ .split(";")[0]
+ .toLowerCase();
+ },
+ requestCode() {
+ if (this.requestType === "JavaScript XHR") {
+ var requestString = [];
+ requestString.push("const xhr = new XMLHttpRequest()");
+ const user = this.auth === "Basic" ? this.httpUser : null;
+ const pswd = this.auth === "Basic" ? this.httpPassword : null;
+ requestString.push(
+ 'xhr.open("' +
+ this.method +
+ '", "' +
+ this.url +
+ this.path +
+ this.queryString +
+ '", true, ' +
+ user +
+ ", " +
+ pswd +
+ ")"
+ );
+ if (this.auth === "Bearer Token") {
+ requestString.push(
+ "xhr.setRequestHeader('Authorization', 'Bearer ' + " +
+ this.bearerToken +
+ ")"
+ );
+ }
+ if (this.headers) {
+ this.headers.forEach(function(element) {
+ requestString.push(
+ "xhr.setRequestHeader(" + element.key + ", " + element.value + ")"
+ );
+ });
+ }
+ if (["POST", "PUT", "PATCH"].includes(this.method)) {
+ const requestBody = this.rawInput
+ ? this.rawParams
+ : this.rawRequestBody;
+ requestString.push(
+ "xhr.setRequestHeader('Content-Length', " + requestBody.length + ")"
+ );
+ requestString.push(
+ "xhr.setRequestHeader('Content-Type', `" +
+ this.contentType +
+ "; charset=utf-8`)"
+ );
+ requestString.push("xhr.send(" + requestBody + ")");
} else {
- return bodyParams
- .filter(({
- key
- }) => !!key)
- .map(({
- key,
- value
- }) => `${key}=${encodeURIComponent(value)}`).join('&')
+ requestString.push("xhr.send()");
}
- },
- headerString() {
- const result = this.headers
- .filter(({
- key
- }) => !!key)
- .map(({
- key,
- value
- }) => `${key}: ${value}`).join(',\n')
- return result === '' ? '' : `${result}`
- },
- queryString() {
- const result = this.params
- .filter(({
- key
- }) => !!key)
- .map(({
- key,
- value
- }) => `${key}=${encodeURIComponent(value)}`).join('&')
- return result === '' ? '' : `?${result}`
- },
- responseType() {
- return (this.response.headers['content-type'] || '').split(';')[0].toLowerCase();
- },
- requestCode() {
- if (this.requestType === 'JavaScript XHR') {
- var requestString = []
- requestString.push('const xhr = new XMLHttpRequest()');
- const user = this.auth === 'Basic' ? this.httpUser : null
- const pswd = this.auth === 'Basic' ? this.httpPassword : null
- requestString.push('xhr.open("' + this.method + '", "' + this.url + this.path + this.queryString + '", true, ' +
- user + ', ' + pswd + ')');
- if (this.auth === 'Bearer Token') {
- requestString.push("xhr.setRequestHeader('Authorization', 'Bearer ' + " + this.bearerToken + ")");
- }
- if (this.headers) {
- this.headers.forEach(function (element) {
- requestString.push('xhr.setRequestHeader(' + element.key + ', ' + element.value + ')');
- })
- }
- if (['POST', 'PUT', 'PATCH'].includes(this.method)) {
- const requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;
- requestString.push("xhr.setRequestHeader('Content-Length', " + requestBody.length + ")")
- requestString.push("xhr.setRequestHeader('Content-Type', `" + this.contentType + "; charset=utf-8`)")
- requestString.push("xhr.send(" + requestBody + ")")
- } else {
- requestString.push('xhr.send()')
- }
- return requestString.join('\n');
- } else if (this.requestType == 'Fetch') {
- var requestString = [];
- var headers = [];
- requestString.push('fetch("' + this.url + this.path + this.queryString + '", {\n')
- requestString.push(' method: "' + this.method + '",\n')
- if (this.auth === 'Basic') {
- var basic = this.httpUser + ':' + this.httpPassword;
- this.$store.commit('addHeaders', ' "Authorization": "Basic ' + window.btoa(unescape(encodeURIComponent(basic))) + ',\n')
- } else if (this.auth === 'Bearer Token') {
- this.$store.commit('addHeaders', ' "Authorization": "Bearer Token ' + this.bearerToken + ',\n')
- }
- if (['POST', 'PUT', 'PATCH'].includes(this.method)) {
- const requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;
- requestString.push(' body: ' + requestBody + ',\n')
- this.$store.commit('addHeaders', ' "Content-Length": ' + requestBody.length + ',\n')
- this.$store.commit('addHeaders', ' "Content-Type": "' + this.contentType + '; charset=utf-8",\n')
- }
- if (this.headers) {
- this.headers.forEach(function (element) {
- this.$store.commit('addHeaders', ' "' + element.key + '": "' + element.value + '",\n')
- })
- }
- headers = headers.join('').slice(0, -3);
- requestString.push(' headers: {\n' + headers + '\n },\n')
- requestString.push(' credentials: "same-origin"\n')
- requestString.push(')}).then(function(response) {\n')
- requestString.push(' response.status\n')
- requestString.push(' response.statusText\n')
- requestString.push(' response.headers\n')
- requestString.push(' response.url\n\n')
- requestString.push(' return response.text()\n')
- requestString.push(')}, function(error) {\n')
- requestString.push(' error.message\n')
- requestString.push(')}')
- return requestString.join('');
- } else if (this.requestType === 'cURL') {
- var requestString = [];
- requestString.push('curl -X ' + this.method + ' \\\n')
- requestString.push(" '" + this.url + this.path + this.queryString + "' \\\n")
- if (this.auth === 'Basic') {
- var basic = this.httpUser + ':' + this.httpPassword;
- requestString.push(" -H 'Authorization: Basic " + window.btoa(unescape(encodeURIComponent(basic))) +
- "' \\\n")
- } else if (this.auth === 'Bearer Token') {
- requestString.push(" -H 'Authorization: Bearer Token " + this.bearerToken + "' \\\n")
- }
- if (this.headers) {
- this.headers.forEach(function (element) {
- requestString.push(" -H '" + element.key + ": " + element.value + "' \\\n");
- })
- }
- if (['POST', 'PUT', 'PATCH'].includes(this.method)) {
- const requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;
- requestString.push(" -H 'Content-Length: " + requestBody.length + "' \\\n")
- requestString.push(" -H 'Content-Type: " + this.contentType + "; charset=utf-8' \\\n")
- requestString.push(" -d '" + requestBody + "' \\\n")
- }
- return requestString.join('').slice(0, -3);
+ return requestString.join("\n");
+ } else if (this.requestType == "Fetch") {
+ var requestString = [];
+ var headers = [];
+ requestString.push(
+ 'fetch("' + this.url + this.path + this.queryString + '", {\n'
+ );
+ requestString.push(' method: "' + this.method + '",\n');
+ if (this.auth === "Basic") {
+ var basic = this.httpUser + ":" + this.httpPassword;
- headers.push(
- ' "Authorization": "Basic ' +
- window.btoa(unescape(encodeURIComponent(basic))) +
- ",\n"
- );
++ this.$store.commit('addHeaders', ' "Authorization": "Basic ' + window.btoa(unescape(encodeURIComponent(basic))) + ",\n")
+ } else if (this.auth === "Bearer Token") {
- headers.push(
- ' "Authorization": "Bearer Token ' + this.bearerToken + ",\n"
- );
++ this.$store.commit('addHeaders', ' "Authorization": "Bearer Token ' + this.bearerToken + ",\n")
}
- }
- },
- methods: {
- handleUseHistory({
- label,
- method,
- url,
- path
- }) {
- this.label = label;
- this.method = method;
- this.url = url;
- this.path = path;
- this.$refs.request.$el.scrollIntoView({
- behavior: 'smooth'
- });
- },
- async makeRequest(auth, headers, requestBody) {
- const requestOptions = {
- method: this.method,
- url: this.url + this.pathName + this.queryString,
- auth,
- headers,
- data: requestBody ? requestBody.toString() : null
- };
-
- const config = this.$store.state.postwoman.settings.PROXY_ENABLED ? {
- method: 'POST',
- url: `${window.location.protocol}//${window.location.host}/proxy`,
- data: requestOptions
- } : requestOptions;
-
- const response = await this.$axios(config);
- return this.$store.state.postwoman.settings.PROXY_ENABLED ? response.data : response;
- },
- async sendRequest() {
- this.$toast.clear();
-
- if (!this.isValidURL) {
- this.$toast.error('URL is not formatted properly', {
- icon: 'error'
+ if (["POST", "PUT", "PATCH"].includes(this.method)) {
+ const requestBody = this.rawInput
+ ? this.rawParams
+ : this.rawRequestBody;
+ requestString.push(" body: " + requestBody + ",\n");
- headers.push(' "Content-Length": ' + requestBody.length + ",\n");
- headers.push(
- ' "Content-Type": "' + this.contentType + '; charset=utf-8",\n'
- );
++ this.$store.commit('addHeaders', ' "Content-Length": ' + requestBody.length + ",\n")
++ this.$store.commit('addHeaders', ' "Content-Type": "' + this.contentType + '; charset=utf-8",\n')
+ }
+ if (this.headers) {
+ this.headers.forEach(function(element) {
- headers.push(
- ' "' + element.key + '": "' + element.value + '",\n'
- );
++ this.$store.commit('addHeaders', ' "' + element.key + '": "' + element.value + '",\n')
});
- return;
}
-
- // Start showing the loading bar as soon as possible.
- // The nuxt axios module will hide it when the request is made.
- this.$nuxt.$loading.start();
-
- if (this.$refs.response.$el.classList.contains('hidden')) {
- this.$refs.response.$el.classList.toggle('hidden')
+ headers = headers.join("").slice(0, -3);
+ requestString.push(" headers: {\n" + headers + "\n },\n");
+ requestString.push(' credentials: "same-origin"\n');
+ requestString.push(")}).then(function(response) {\n");
+ requestString.push(" response.status\n");
+ requestString.push(" response.statusText\n");
+ requestString.push(" response.headers\n");
+ requestString.push(" response.url\n\n");
+ requestString.push(" return response.text()\n");
+ requestString.push(")}, function(error) {\n");
+ requestString.push(" error.message\n");
+ requestString.push(")}");
+ return requestString.join("");
+ } else if (this.requestType === "cURL") {
+ var requestString = [];
+ requestString.push("curl -X " + this.method + " \\\n");
+ requestString.push(
+ " '" + this.url + this.path + this.queryString + "' \\\n"
+ );
+ if (this.auth === "Basic") {
+ var basic = this.httpUser + ":" + this.httpPassword;
+ requestString.push(
+ " -H 'Authorization: Basic " +
+ window.btoa(unescape(encodeURIComponent(basic))) +
+ "' \\\n"
+ );
+ } else if (this.auth === "Bearer Token") {
+ requestString.push(
+ " -H 'Authorization: Bearer Token " + this.bearerToken + "' \\\n"
+ );
}
- this.$refs.response.$el.scrollIntoView({
- behavior: 'smooth'
- });
- this.previewEnabled = false;
- this.response.status = 'Fetching...';
- this.response.body = 'Loading...';
+ if (this.headers) {
+ this.headers.forEach(function(element) {
+ requestString.push(
+ " -H '" + element.key + ": " + element.value + "' \\\n"
+ );
+ });
+ }
+ if (["POST", "PUT", "PATCH"].includes(this.method)) {
+ const requestBody = this.rawInput
+ ? this.rawParams
+ : this.rawRequestBody;
+ requestString.push(
+ " -H 'Content-Length: " + requestBody.length + "' \\\n"
+ );
+ requestString.push(
+ " -H 'Content-Type: " + this.contentType + "; charset=utf-8' \\\n"
+ );
+ requestString.push(" -d '" + requestBody + "' \\\n");
+ }
+ return requestString.join("").slice(0, -3);
+ }
+ }
+ },
+ methods: {
+ handleUseHistory({ label, method, url, path }) {
+ this.label = label;
+ this.method = method;
+ this.url = url;
+ this.path = path;
+ this.$refs.request.$el.scrollIntoView({
+ behavior: "smooth"
+ });
+ },
+ async makeRequest(auth, headers, requestBody) {
+ const requestOptions = {
+ method: this.method,
+ url: this.url + this.pathName + this.queryString,
+ auth,
+ headers,
+ data: requestBody ? requestBody.toString() : null
+ };
- const auth = this.auth === 'Basic' ? {
- username: this.httpUser,
- password: this.httpPassword
- } : null;
+ const config = this.$store.state.postwoman.settings.PROXY_ENABLED
+ ? {
+ method: "POST",
+ url: `https://postwoman.apollotv.xyz/`,
+ data: requestOptions
+ }
+ : requestOptions;
- let headers = {};
- let headersObject = {};
+ const response = await this.$axios(config);
+ return this.$store.state.postwoman.settings.PROXY_ENABLED
+ ? response.data
+ : response;
+ },
+ async sendRequest() {
+ this.$toast.clear();
- Object.keys(headers).forEach(id => {
- headersObject[headers[id].key] = headers[id].value
+ if (!this.isValidURL) {
+ this.$toast.error("URL is not formatted properly", {
+ icon: "error"
});
- headers = headersObject;
+ return;
+ }
- // If the request has a body, we want to ensure Content-Length and
- // Content-Type are sent.
- let requestBody;
- if (this.hasRequestBody) {
- requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;
+ // Start showing the loading bar as soon as possible.
+ // The nuxt axios module will hide it when the request is made.
+ this.$nuxt.$loading.start();
- Object.assign(headers, {
- //'Content-Length': requestBody.length,
- 'Content-Type': `${this.contentType}; charset=utf-8`
- });
- }
+ if (this.$refs.response.$el.classList.contains("hidden")) {
+ this.$refs.response.$el.classList.toggle("hidden");
+ }
+ this.$refs.response.$el.scrollIntoView({
+ behavior: "smooth"
+ });
+ this.previewEnabled = false;
+ this.response.status = "Fetching...";
+ this.response.body = "Loading...";
+
+ const auth =
+ this.auth === "Basic"
+ ? {
+ username: this.httpUser,
+ password: this.httpPassword
+ }
+ : null;
- // If the request uses a token for auth, we want to make sure it's sent here.
- if (this.auth === 'Bearer Token') headers['Authorization'] = `Bearer ${this.bearerToken}`;
+ let headers = {};
+ let headersObject = {};
- headers = Object.assign(
- // Clone the app headers object first, we don't want to
- // mutate it with the request headers added by default.
- Object.assign({}, this.headers),
+ Object.keys(headers).forEach(id => {
+ headersObject[headers[id].key] = headers[id].value;
+ });
+ headers = headersObject;
- // We make our temporary headers object the source so
- // that you can override the added headers if you
- // specify them.
- headers
- );
+ // If the request has a body, we want to ensure Content-Length and
+ // Content-Type are sent.
+ let requestBody;
+ if (this.hasRequestBody) {
+ requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;
- Object.keys(headers).forEach(id => {
- headersObject[headers[id].key] = headers[id].value
+ Object.assign(headers, {
+ //'Content-Length': requestBody.length,
+ "Content-Type": `${this.contentType}; charset=utf-8`
});
- headers = headersObject;
+ }
- try {
- const startTime = Date.now();
+ // If the request uses a token for auth, we want to make sure it's sent here.
+ if (this.auth === "Bearer Token")
+ headers["Authorization"] = `Bearer ${this.bearerToken}`;
- const payload = await this.makeRequest(auth, headers, requestBody);
+ headers = Object.assign(
+ // Clone the app headers object first, we don't want to
+ // mutate it with the request headers added by default.
+ Object.assign({}, this.headers),
- const duration = Date.now() - startTime;
- this.$toast.info(`Finished in ${duration}ms`, {
- icon: 'done'
- });
+ // We make our temporary headers object the source so
+ // that you can override the added headers if you
+ // specify them.
+ headers
+ );
- (() => {
- const status = this.response.status = payload.status;
- const headers = this.response.headers = payload.headers;
+ Object.keys(headers).forEach(id => {
+ headersObject[headers[id].key] = headers[id].value;
+ });
+ headers = headersObject;
- // We don't need to bother parsing JSON, axios already handles it for us!
- const body = this.response.body = payload.data;
+ try {
+ const startTime = Date.now();
- const date = new Date().toLocaleDateString();
- const time = new Date().toLocaleTimeString();
+ const payload = await this.makeRequest(auth, headers, requestBody);
- // Addition of an entry to the history component.
- const entry = {
- label: this.requestName,
- status,
- date,
- time,
- method: this.method,
- url: this.url,
- path: this.path
- };
- this.$refs.historyComponent.addEntry(entry);
- })();
- } catch (error) {
- console.error(error);
- if (error.response) {
- this.response.headers = error.response.headers;
- this.response.status = error.response.status;
- this.response.body = error.response.data;
+ const duration = Date.now() - startTime;
+ this.$toast.info(`Finished in ${duration}ms`, {
+ icon: "done"
+ });
- // Addition of an entry to the history component.
- const entry = {
- label: this.requestName,
- status: this.response.status,
- date: new Date().toLocaleDateString(),
- time: new Date().toLocaleTimeString(),
- method: this.method,
- url: this.url,
- path: this.path
- };
- this.$refs.historyComponent.addEntry(entry);
- return;
- } else {
- this.response.status = error.message;
- this.response.body = "See JavaScript console (F12) for details.";
- this.$toast.error(error + ' (F12 for details)', {
- icon: 'error'
- });
- if(!this.$store.state.postwoman.settings.PROXY_ENABLED) {
- this.$toast.info('Try enabling Proxy', {
- icon: 'help',
- duration: 5000,
- action: {
- text: 'Settings',
- onClick: (e, toastObject) => {
- this.$router.push({ path: '/settings' });
- }
- }
- });
- }
- }
- }
- },
- getQueryStringFromPath() {
- let queryString,
- pathParsed = url.parse(this.path);
- return queryString = pathParsed.query ? pathParsed.query : '';
- },
- queryStringToArray(queryString) {
- let queryParsed = querystring.parse(queryString);
- return Object.keys(queryParsed).map((key) => ({key: key, value: queryParsed[key]}))
- },
- pathInputHandler() {
- let queryString = this.getQueryStringFromPath(),
- params = this.queryStringToArray(queryString);
+ (() => {
+ const status = (this.response.status = payload.status);
+ const headers = (this.response.headers = payload.headers);
- this.paramsWatchEnabled = false;
- this.params = params;
- },
- addRequestHeader() {
- this.$store.commit('addHeaders', {
- key: '',
- value: ''
- })
- return false
- },
- removeRequestHeader(index) {
- this.$store.commit('removeHeaders', index)
- this.$toast.error('Deleted', {
- icon: 'delete'
- });
- },
- addRequestParam() {
- this.$store.commit('addParams', { key: '', value: '' })
+ // We don't need to bother parsing JSON, axios already handles it for us!
+ const body = (this.response.body = payload.data);
- return false
- },
- removeRequestParam(index) {
- this.$store.commit('removeParams', index)
- this.$toast.error('Deleted', {
- icon: 'delete'
- });
- },
- addRequestBodyParam() {
- this.$store.commit('addBodyParams', { key: '', value: '' })
+ const date = new Date().toLocaleDateString();
+ const time = new Date().toLocaleTimeString();
- return false
- },
- removeRequestBodyParam(index) {
- this.$store.commit('removeBodyParams', index)
- this.$toast.error('Deleted', {
- icon: 'delete'
- });
- },
- formatRawParams(event) {
- if ((event.which !== 13 && event.which !== 9)) {
+ // Addition of an entry to the history component.
+ const entry = {
+ label: this.requestName,
+ status,
+ date,
+ time,
+ method: this.method,
+ url: this.url,
+ path: this.path
+ };
+ this.$refs.historyComponent.addEntry(entry);
+ })();
+ } catch (error) {
+ console.error(error);
+ if (error.response) {
+ this.response.headers = error.response.headers;
+ this.response.status = error.response.status;
+ this.response.body = error.response.data;
+
+ // Addition of an entry to the history component.
+ const entry = {
+ label: this.requestName,
+ status: this.response.status,
+ date: new Date().toLocaleDateString(),
+ time: new Date().toLocaleTimeString(),
+ method: this.method,
+ url: this.url,
+ path: this.path
+ };
+ this.$refs.historyComponent.addEntry(entry);
return;
- }
- const textBody = event.target.value;
- const textBeforeCursor = textBody.substring(0, event.target.selectionStart);
- const textAfterCursor = textBody.substring(event.target.selectionEnd);
- if (event.which === 13) {
- event.preventDefault();
- const oldSelectionStart = event.target.selectionStart;
- const lastLine = textBeforeCursor.split('\n').slice(-1)[0];
- const rightPadding = lastLine.match(/([\s\t]*).*/)[1] || "";
- event.target.value = textBeforeCursor + '\n' + rightPadding + textAfterCursor;
- setTimeout(() => event.target.selectionStart = event.target.selectionEnd = oldSelectionStart + rightPadding
- .length + 1, 1);
- } else if (event.which === 9) {
- event.preventDefault();
- const oldSelectionStart = event.target.selectionStart;
- event.target.value = textBeforeCursor + '\xa0\xa0' + textAfterCursor;
- event.target.selectionStart = event.target.selectionEnd = oldSelectionStart + 2;
- return false;
- }
- },
- copyRequest() {
- if (navigator.share) {
- let time = new Date().toLocaleTimeString();
- let date = new Date().toLocaleDateString();
- navigator.share({
- title: `Postwoman`,
- text: `Postwoman • API request builder at ${time} on ${date}`,
- url: window.location.href
- }).then(() => {})
- .catch(console.error);
} else {
- var dummy = document.createElement('input');
- document.body.appendChild(dummy);
- dummy.value = window.location.href;
- dummy.select();
- document.execCommand('copy');
- document.body.removeChild(dummy);
- this.$refs.copyRequest.innerHTML = this.copiedButton;
- this.$toast.success('Copied to clipboard', {
- icon: 'done'
+ this.response.status = error.message;
+ this.response.body = "See JavaScript console (F12) for details.";
+ this.$toast.error(error + " (F12 for details)", {
+ icon: "error"
});
- setTimeout(() => this.$refs.copyRequest.innerHTML = '<i class="material-icons">share</i>', 1000)
+ if (!this.$store.state.postwoman.settings.PROXY_ENABLED) {
+ this.$toast.info("Try enabling Proxy", {
+ icon: "help",
+ duration: 5000,
+ action: {
+ text: "Settings",
+ onClick: (e, toastObject) => {
+ this.$router.push({ path: "/settings" });
+ }
+ }
+ });
+ }
}
- },
- copyRequestCode() {
- this.$refs.copyRequestCode.innerHTML = this.copiedButton + '<span>Copied</span>';
- this.$toast.success('Copied to clipboard', {
- icon: 'done'
- });
- this.$refs.generatedCode.select();
+ }
+ },
+ getQueryStringFromPath() {
+ let queryString,
+ pathParsed = url.parse(this.path);
+ return (queryString = pathParsed.query ? pathParsed.query : "");
+ },
+ queryStringToArray(queryString) {
+ let queryParsed = querystring.parse(queryString);
+ return Object.keys(queryParsed).map(key => ({
+ key: key,
+ value: queryParsed[key]
+ }));
+ },
+ pathInputHandler() {
+ let queryString = this.getQueryStringFromPath(),
+ params = this.queryStringToArray(queryString);
+
+ this.paramsWatchEnabled = false;
+ this.params = params;
+ },
+ addRequestHeader() {
- this.headers.push({
++ this.$store.commit('addHeaders', {
+ key: "",
+ value: ""
+ });
+ return false;
+ },
+ removeRequestHeader(index) {
- this.headers.splice(index, 1);
++ this.$store.commit('removeHeaders', index)
+ this.$toast.error("Deleted", {
+ icon: "delete"
+ });
+ },
+ addRequestParam() {
- this.params.push({
- key: "",
- value: ""
- });
++ this.$store.commit('addParams', { key: "", value: "" })
+ return false;
+ },
+ removeRequestParam(index) {
- this.params.splice(index, 1);
++ this.$store.commit('removeParams', index)
+ this.$toast.error("Deleted", {
+ icon: "delete"
+ });
+ },
+ addRequestBodyParam() {
- this.bodyParams.push({
- key: "",
- value: ""
- });
++ this.$store.commit('addBodyParams', { key: "", value: "" })
+ return false;
+ },
+ removeRequestBodyParam(index) {
- this.bodyParams.splice(index, 1);
++ this.$store.commit('removeBodyParams', index)
+ this.$toast.error("Deleted", {
+ icon: "delete"
+ });
+ },
+ formatRawParams(event) {
+ if (event.which !== 13 && event.which !== 9) {
+ return;
+ }
+ const textBody = event.target.value;
+ const textBeforeCursor = textBody.substring(
+ 0,
+ event.target.selectionStart
+ );
+ const textAfterCursor = textBody.substring(event.target.selectionEnd);
+ if (event.which === 13) {
+ event.preventDefault();
+ const oldSelectionStart = event.target.selectionStart;
+ const lastLine = textBeforeCursor.split("\n").slice(-1)[0];
+ const rightPadding = lastLine.match(/([\s\t]*).*/)[1] || "";
+ event.target.value =
+ textBeforeCursor + "\n" + rightPadding + textAfterCursor;
+ setTimeout(
+ () =>
+ (event.target.selectionStart = event.target.selectionEnd =
+ oldSelectionStart + rightPadding.length + 1),
+ 1
+ );
+ } else if (event.which === 9) {
+ event.preventDefault();
+ const oldSelectionStart = event.target.selectionStart;
+ event.target.value = textBeforeCursor + "\xa0\xa0" + textAfterCursor;
+ event.target.selectionStart = event.target.selectionEnd =
+ oldSelectionStart + 2;
+ return false;
+ }
+ },
+ copyRequest() {
+ if (navigator.share) {
+ let time = new Date().toLocaleTimeString();
+ let date = new Date().toLocaleDateString();
+ navigator
+ .share({
+ title: `Postwoman`,
+ text: `Postwoman • API request builder at ${time} on ${date}`,
+ url: window.location.href
+ })
+ .then(() => {})
+ .catch(console.error);
+ } else {
+ var dummy = document.createElement("input");
+ document.body.appendChild(dummy);
+ dummy.value = window.location.href;
+ dummy.select();
document.execCommand("copy");
- setTimeout(() => this.$refs.copyRequestCode.innerHTML = this.copyButton + '<span>Copy</span>', 1000)
- },
- copyResponse() {
- this.$refs.copyResponse.innerHTML = this.copiedButton + '<span>Copied</span>';
- this.$toast.success('Copied to clipboard', {
- icon: 'done'
+ document.body.removeChild(dummy);
+ this.$refs.copyRequest.innerHTML = this.copiedButton;
+ this.$toast.info("Copied to clipboard", {
+ icon: "done"
});
- // Creates a textarea element
- var aux = document.createElement("textarea");
- var copy = this.responseType == 'application/json' ? JSON.stringify(this.response.body) : this.response.body;
- // Adds response body to the new textarea
- aux.innerText = copy;
- // Append the textarea to the body
- document.body.appendChild(aux);
- // Highlight the content
- aux.select();
- document.execCommand('copy');
- // Remove the input from the body
- document.body.removeChild(aux);
- setTimeout(() => this.$refs.copyResponse.innerHTML = this.copyButton + '<span>Copy</span>', 1000)
- },
- togglePreview() {
- this.previewEnabled = !this.previewEnabled;
- if (this.previewEnabled) {
- // If you want to add 'preview' support for other response types,
- // just add them here.
- if (this.responseType === "text/html") {
- // If the preview already has that URL loaded, let's not bother re-loading it all.
- if (this.$refs.previewFrame.getAttribute('data-previewing-url') === this.url)
- return;
- // Use DOMParser to parse document HTML.
- const previewDocument = new DOMParser().parseFromString(this.response.body, this.responseType);
- // Inject <base href="..."> tag to head, to fix relative CSS/HTML paths.
- previewDocument.head.innerHTML = `<base href="${this.url}">` + previewDocument.head.innerHTML;
- // Finally, set the iframe source to the resulting HTML.
- this.$refs.previewFrame.srcdoc = previewDocument.documentElement.outerHTML;
- this.$refs.previewFrame.setAttribute('data-previewing-url', this.url);
- }
- }
- },
- setRouteQueryState() {
- const flat = key => this[key] !== '' ? `${key}=${this[key]}&` : ''
- const deep = key => {
- const haveItems = [...this[key]].length
- if (haveItems && this[key]['value'] !== '') {
- return `${key}=${JSON.stringify(this[key])}&`
- } else return ''
+ setTimeout(
+ () =>
+ (this.$refs.copyRequest.innerHTML =
+ '<i class="material-icons">file_copy</i>'),
+ 1000
+ );
+ }
+ },
+ copyRequestCode() {
+ this.$refs.copyRequestCode.innerHTML =
+ this.copiedButton + "<span>Copied</span>";
+ this.$toast.success("Copied to clipboard", {
+ icon: "done"
+ });
+ this.$refs.generatedCode.select();
+ document.execCommand("copy");
+ setTimeout(
+ () =>
+ (this.$refs.copyRequestCode.innerHTML =
+ this.copyButton + "<span>Copy</span>"),
+ 1000
+ );
+ },
+ copyResponse() {
+ this.$refs.copyResponse.innerHTML =
+ this.copiedButton + "<span>Copied</span>";
+ this.$toast.success("Copied to clipboard", {
+ icon: "done"
+ });
+ // Creates a textarea element
+ var aux = document.createElement("textarea");
+ var copy =
+ this.responseType == "application/json"
+ ? JSON.stringify(this.response.body)
+ : this.response.body;
+ // Adds response body to the new textarea
+ aux.innerText = copy;
+ // Append the textarea to the body
+ document.body.appendChild(aux);
+ // Highlight the content
+ aux.select();
+ document.execCommand("copy");
+ // Remove the input from the body
+ document.body.removeChild(aux);
+ setTimeout(
+ () =>
+ (this.$refs.copyResponse.innerHTML =
+ this.copyButton + "<span>Copy</span>"),
+ 1000
+ );
+ },
+ togglePreview() {
+ this.previewEnabled = !this.previewEnabled;
+ if (this.previewEnabled) {
+ // If you want to add 'preview' support for other response types,
+ // just add them here.
+ if (this.responseType === "text/html") {
+ // If the preview already has that URL loaded, let's not bother re-loading it all.
+ if (
+ this.$refs.previewFrame.getAttribute("data-previewing-url") ===
+ this.url
+ )
+ return;
+ // Use DOMParser to parse document HTML.
+ const previewDocument = new DOMParser().parseFromString(
+ this.response.body,
+ this.responseType
+ );
+ // Inject <base href="..."> tag to head, to fix relative CSS/HTML paths.
+ previewDocument.head.innerHTML =
+ `<base href="${this.url}">` + previewDocument.head.innerHTML;
+ // Finally, set the iframe source to the resulting HTML.
+ this.$refs.previewFrame.srcdoc =
+ previewDocument.documentElement.outerHTML;
+ this.$refs.previewFrame.setAttribute("data-previewing-url", this.url);
}
- let flats = ['method', 'url', 'path', 'auth', 'httpUser', 'httpPassword', 'bearerToken', 'contentType'].map(
- item => flat(item))
- let deeps = ['headers', 'params'].map(item => deep(item))
- let bodyParams = this.rawInput ? [flat('rawParams')] : [deep('bodyParams')];
+ }
+ },
+ setRouteQueryState() {
+ const flat = key => (this[key] !== "" ? `${key}=${this[key]}&` : "");
+ const deep = key => {
+ const haveItems = [...this[key]].length;
+ if (haveItems && this[key]["value"] !== "") {
+ return `${key}=${JSON.stringify(this[key])}&`;
+ } else return "";
+ };
+ let flats = [
+ "method",
+ "url",
+ "path",
+ !this.urlExcludes.auth ? "auth" : null,
+ "httpUser",
+ "httpPassword",
+ "bearerToken",
+ "contentType"
+ ].filter((item) => item !== null).map(item => flat(item));
+ let deeps = ["headers", "params"].map(item => deep(item));
+ let bodyParams = this.rawInput
+ ? [flat("rawParams")]
+ : [deep("bodyParams")];
- this.$router.replace('/?' + flats.concat(deeps, bodyParams).join('').slice(0, -1))
- },
- setRouteQueries(queries) {
- if (typeof (queries) !== 'object') throw new Error('Route query parameters must be a Object')
- for (const key in queries) {
- if (['headers', 'params', 'bodyParams'].includes(key)) this[key] = JSON.parse(queries[key])
- if (key === 'rawParams') {
- this.rawInput = true
- this.rawParams = queries['rawParams']
- } else if (typeof (this[key]) === 'string') this[key] = queries[key]
- }
- },
- observeRequestButton() {
- const requestElement = this.$refs.request.$el;
- const sendButtonElement = this.$refs.sendButton;
- const observer = new IntersectionObserver((entries, observer) => {
+ this.$router.replace(
+ "/?" +
+ flats
+ .concat(deeps, bodyParams)
+ .join("")
+ .slice(0, -1)
+ );
+ },
+ setRouteQueries(queries) {
+ if (typeof queries !== "object")
+ throw new Error("Route query parameters must be a Object");
+ for (const key in queries) {
+ if (["headers", "params", "bodyParams"].includes(key))
+ this[key] = JSON.parse(queries[key]);
+ if (key === "rawParams") {
+ this.rawInput = true;
+ this.rawParams = queries["rawParams"];
+ } else if (typeof this[key] === "string") this[key] = queries[key];
+ }
+ },
+ observeRequestButton() {
+ const requestElement = this.$refs.request.$el;
+ const sendButtonElement = this.$refs.sendButton;
+ const observer = new IntersectionObserver(
+ (entries, observer) => {
entries.forEach(entry => {
- if(entry.isIntersecting) sendButtonElement.classList.remove('show');
+ if (entry.isIntersecting)
+ sendButtonElement.classList.remove("show");
// The button should float when it is no longer visible on screen.
// This is done by adding the show class to the button.
- else sendButtonElement.classList.add('show');
- });
- }, {
- rootMargin: '0px',
- threshold: [0],
- });
- observer.observe(requestElement);
- },
- handleImport() {
- let textarea = document.getElementById("import-text")
- let text = textarea.value;
- try {
- let parsedCurl = parseCurlCommand(text);
- this.url = parsedCurl.url.replace(/"/g,"").replace(/'/g,"");
- this.url = this.url.slice(-1).pop() == '/' ? this.url.slice(0, -1): this.url;
- this.path = "";
- this.headers = [];
- for (const key of Object.keys(parsedCurl.headers)) {
- this.$store.commit('addHeaders', { key: key, value: parsedCurl.headers[key] })
- }
- this.method = parsedCurl.method.toUpperCase();
- if (parsedCurl["data"]){
- this.rawInput = true;
- this.rawParams = parsedCurl["data"];
- }
- this.showModal = false;
- } catch (error) {
- this.showModal = false;
- this.$toast.error('cURL is not formatted properly', {
- icon: 'error'
+ else sendButtonElement.classList.add("show");
});
+ },
+ {
+ rootMargin: "0px",
+ threshold: [0]
}
- },
- toggleModal() {
- this.showModal = !this.showModal;
- },
- switchVisibility() {
- this.passwordFieldType = this.passwordFieldType === 'password' ? 'text' : 'password'
- },
- clearContent(name) {
- switch(name) {
- case "auth":
- this.auth = 'None';
- this.httpUser = '';
- this.httpPassword = '';
- break;
- case "headers":
- this.headers = [];
- break;
- case "parameters":
- this.params = [];
- break;
- default:
- this.label = '',
- this.method= 'GET',
- this.url = 'https://reqres.in',
- this.auth = 'None',
- this.path = '/api/users',
- this.auth = 'None';
- this.httpUser = '';
- this.httpPassword = '';
- this.headers = [];
- this.params = [];
- this.bodyParams = [];
- this.rawParams = '';
+ );
+ observer.observe(requestElement);
+ },
+ handleImport() {
+ let textarea = document.getElementById("import-text");
+ let text = textarea.value;
+ try {
+ let parsedCurl = parseCurlCommand(text);
+ this.url = parsedCurl.url.replace(/"/g, "").replace(/'/g, "");
+ this.url =
+ this.url.slice(-1).pop() == "/" ? this.url.slice(0, -1) : this.url;
+ this.path = "";
+ this.headers = [];
+ for (const key of Object.keys(parsedCurl.headers)) {
- this.headers.push({
- key: key,
- value: parsedCurl.headers[key]
- });
++ this.$store.commit('addHeaders', { key: key, value: parsedCurl.headers[key] })
+ }
+ this.method = parsedCurl.method.toUpperCase();
+ if (parsedCurl["data"]) {
+ this.rawInput = true;
+ this.rawParams = parsedCurl["data"];
}
- this.$toast.info('Cleared', {
- icon: 'clear_all'
+ this.showModal = false;
+ } catch (error) {
+ this.showModal = false;
+ this.$toast.error("cURL is not formatted properly", {
+ icon: "error"
});
- },
- saveRequest() {
- this.editRequest = {
- url: this.url,
- path: this.path,
- method: this.method,
- auth: this.auth,
- httpUser: this.httpUser,
- httpPassword: this.httpPassword,
- passwordFieldType: this.passwordFieldType,
- bearerToken: this.bearerToken,
- headers: this.headers,
- params: this.params,
- bodyParams: this.bodyParams,
- rawParams: this.rawParams,
- rawInput: this.rawInput,
- contentType: this.contentType,
- requestType: this.requestType,
- };
+ }
+ },
+ toggleModal() {
+ this.showModal = !this.showModal;
+ },
+ switchVisibility() {
+ this.passwordFieldType =
+ this.passwordFieldType === "password" ? "text" : "password";
+ },
+ clearContent(name) {
+ switch (name) {
+ case "auth":
+ this.auth = "None";
+ this.httpUser = "";
+ this.httpPassword = "";
+ this.bearerToken = "";
+ break;
+ case "headers":
+ this.headers = [];
+ break;
+ case "parameters":
+ this.params = [];
+ break;
+ default:
+ (this.label = ""),
+ (this.method = "GET"),
+ (this.url = "https://reqres.in"),
+ (this.auth = "None"),
+ (this.path = "/api/users"),
+ (this.auth = "None");
+ this.httpUser = "";
+ this.httpPassword = "";
+ this.bearerToken = "";
+ this.headers = [];
+ this.params = [];
+ this.bodyParams = [];
+ this.rawParams = "";
+ }
+ this.$toast.info("Cleared", {
+ icon: "clear_all"
+ });
+ },
+ saveRequest() {
+ this.editRequest = {
+ url: this.url,
+ path: this.path,
+ method: this.method,
+ auth: this.auth,
+ httpUser: this.httpUser,
+ httpPassword: this.httpPassword,
+ passwordFieldType: this.passwordFieldType,
+ bearerToken: this.bearerToken,
+ headers: this.headers,
+ params: this.params,
+ bodyParams: this.bodyParams,
+ rawParams: this.rawParams,
+ rawInput: this.rawInput,
+ contentType: this.contentType,
+ requestType: this.requestType
+ };
- if (this.selectedRequest.url) {
- this.editRequest = Object.assign({}, this.selectedRequest, this.editRequest);
- }
+ if (this.selectedRequest.url) {
+ this.editRequest = Object.assign(
+ {},
+ this.selectedRequest,
+ this.editRequest
+ );
+ }
- this.showRequestModal = true;
- },
- hideRequestModal() {
- this.showRequestModal = false;
- this.editRequest = {};
- },
+ this.showRequestModal = true;
},
- mounted() {
- this.observeRequestButton();
+ hideRequestModal() {
+ this.showRequestModal = false;
+ this.editRequest = {};
},
- created() {
- if (Object.keys(this.$route.query).length) this.setRouteQueries(this.$route.query);
- this.$watch(vm => [
+ setExclude (excludedField, excluded) {
+ this.urlExcludes[excludedField] = excluded;
+ this.setRouteQueryState();
++ },
++ methodChange() {
++ this.$store.commit('setState', { 'value': ["POST", "PUT", "PATCH"].includes(this.method) ? 'application/json' : '', 'attribute': 'contentType' })
+ }
+ },
+ mounted() {
+ this.observeRequestButton();
+ },
+ created() {
+ this.urlExcludes = this.$store.state.postwoman.settings.URL_EXCLUDES || {
+ // Exclude authentication by default for security reasons.
+ auth: true
+ };
+
+ if (Object.keys(this.$route.query).length)
+ this.setRouteQueries(this.$route.query);
+ this.$watch(
+ vm => [
vm.label,
vm.method,
vm.url,
@@@ -1280,9 -1517,11 +1560,11 @@@
vm.bodyParams,
vm.contentType,
vm.rawParams
- ], val => {
- this.setRouteQueryState()
- })
- }
+ ],
+ val => {
+ this.setRouteQueryState();
+ }
+ );
}
- </script>
+ };
-</script>
++</script>