forked from postmanlabs/httpsnippet-fsless
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxhr.js
More file actions
80 lines (63 loc) · 2.14 KB
/
xhr.js
File metadata and controls
80 lines (63 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* @description
* HTTP code snippet generator for native XMLHttpRequest
*
* @author
* @AhmadNassri
*
* for any questions or issues regarding the generated code snippet, please open an issue mentioning the author.
*/
'use strict'
var util = require('util')
var CodeBuilder = require('../../helpers/code-builder')
module.exports = function (source, options) {
var opts = util._extend({
indent: ' ',
cors: true
}, options)
var code = new CodeBuilder(opts.indent)
switch (source.postData.mimeType) {
case 'application/json':
code.push('var data = JSON.stringify(%s);', JSON.stringify(source.postData.jsonObj, null, opts.indent))
.push(null)
break
case 'multipart/form-data':
code.push('var data = new FormData();')
source.postData.params.map(function (param) {
code.push('data.append(%s, %s);', JSON.stringify(param.name), JSON.stringify(param.value || param.fileName || ''))
})
// remove the contentType header
if (source.allHeaders['content-type'].indexOf('boundary')) {
delete source.allHeaders['content-type']
}
code.blank()
break
default:
code.push('var data = %s;', JSON.stringify(source.postData.text || null))
.blank()
}
code.push('var xhr = new XMLHttpRequest();')
if (opts.cors) {
code.push('xhr.withCredentials = true;')
}
code.blank()
.push('xhr.addEventListener("readystatechange", function () {')
.push(1, 'if (this.readyState === 4) {')
.push(2, 'console.log(this.responseText);')
.push(1, '}')
.push('});')
.blank()
.push('xhr.open(%s, %s);', JSON.stringify(source.method), JSON.stringify(source.fullUrl))
Object.keys(source.allHeaders).map(function (key) {
code.push('xhr.setRequestHeader(%s, %s);', JSON.stringify(key), JSON.stringify(source.allHeaders[key]))
})
code.blank()
.push('xhr.send(data);')
return code.join()
}
module.exports.info = {
key: 'xhr',
title: 'XMLHttpRequest',
link: 'https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest',
description: 'W3C Standard API that provides scripted client functionality'
}