session.reset = function() { _session = {}; jar.set(cookie, qs.stringify(_session), options); }
module.exports = function(gulp, config) { const autoprefixerOptions = { 'browsers': 'last 3 Chrome versions' }; const babelOptions = { loose: 'all', externalHelpers: true, cacheDirectory: !config.production, blacklist: ['useStrict', 'es6.constants'], optional: ['es7.classProperties'], stage: 0, plugins: [] }; if (config.production) { babelOptions.plugins.push(/* @todo it doesn't work 'remove-console', 'remove-debugger' */); } else { babelOptions.optional.push('validation.react'); } const cssLoaderQuery = { sourceMap: null }; if (!config.production) { cssLoaderQuery.localIdentName = '[local]_[hash:base64:7]'; } const baseWebpackConfig = { stats: { colors: true }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules\/(?!@twic)/, loader: 'babel-loader', query: babelOptions }, { test: /\.(jpe?g|png|gif|svg)$/i, loaders: [ 'file?name=images/[path][name].[ext]' ] }, { test: /\.styl$/, loader: ExtractTextPlugin.extract( 'style-loader', [ 'css-loader?' + qs.stringify(cssLoaderQuery, { strictNullHandling: true }), 'autoprefixer-loader?' + JSON.stringify(autoprefixerOptions), 'stylus-loader' ].join('!') ) } ] } }; if (!config.production) { baseWebpackConfig.debug = true; baseWebpackConfig.devtool = '#cheap-module-source-map'; } // --- config.webpack = function(opts) { const options = _.assign({ vendor: true, watch: false, target: 'web' }, opts); const webpackConfig = _.clone(baseWebpackConfig); const plugins = [ new ExtractTextPlugin('[name].css') ]; if (options.vendor) { plugins.push( new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js') ); } if (config.production) { /*eslint camelcase: 0*/ plugins.push( new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), // --- new webpack.optimize.DedupePlugin(), // --- new webpack.optimize.UglifyJsPlugin({ mangle: { screw_ie8: true }, compressor: { screw_ie8: true, warnings: false } }) ); } if (options.watch) { webpackConfig.watch = true; webpackConfig.stats.reasons = true; webpackConfig.stats.modules = true; } webpackConfig.plugins = plugins; webpackConfig.target = options.target; return webpackConfig; }; };
function userLocations(search, roles) { var url = `${config.backend_url}/accounts/user_locations/?${qs.stringify({search: search, 'roles[]': roles}, {indices: false})}`; return Rx.DOM.get(url).map(xhr => JSON.parse(xhr.responseText)); }
function getUrl( filename, hash ) { return URL_BASE_PATH + '/' + filename + '?' + qs.stringify( { v: hash } ); }
export const userLogin = params => { return axios.post('/user/v1.0/login', qs.stringify(params)).then(res => res.data); };
recipes: (root, { ingredient }) => edamamApiClient.get(`/search?${qs.stringify({ q: ingredient, app_id: process.env.APP_ID, app_key: process.env.APP_KEY })}`).then(({ data }) => data)
if (typeof responseJSON.predictions !== 'undefined') { if (this.isMounted()) { this._results = responseJSON.predictions; this.setState({ dataSource: this.state.dataSource.cloneWithRows(responseJSON.predictions), }); } } if (typeof responseJSON.error_message !== 'undefined') { console.warn('google places autocomplete: ' + responseJSON.error_message); } } else { // console.warn("google places autocomplete: request could not be completed or has been aborted"); } }; request.open('GET', 'https://maps.googleapis.com/maps/api/place/autocomplete/json?&input=' + encodeURI(text) + '&' + Qs.stringify(this.props.query)); request.send(); } else { this._results = []; this.setState({ dataSource: this.state.dataSource.cloneWithRows([]), }); } }, _onChangeText(text) { console.log('changing tetx') if(this.props.data) { var data = this.props.data; var limitItems = this.props.limitItems?this.props.limitItems:6
credentials.signRequest(webResource, function () { assert.equal('/images/pic1.png?comp=metadata&' + qs.stringify(queryString), webResource.requestUrl); done(); });
form.parse(obj, function (err, fields, files) { if (err) { throw err; } fields = querystring.parse(querystring.stringify(fields)); f.handle(fields, callbacks); });
/** * Make a web request * * Options: * * - `uri` || `url` - fully qualified uri or parsed url object from `url.parse()` * - `method` - http method (default: `"GET"`) * - `qs` - object containing querystring values to be appended to the `uri` * - `headers` - http headers (default: `{}`) * - `body` - entity body for PATCH, POST and PUT requests. Must be a `Buffer` or `String`. * - `auth` - A hash containing values `user` || `username`, `password` || `pass` * - `encoding` - encoding to stringify the result body, set this to `null` to get a `Buffer` * * @param {String} uri * @param {Object} options * @return {Response} */ function request(uri, options) { // 1 - handle variable list of arguments if (typeof uri === 'undefined') { throw new TypeError('undefined is not a valid uri or options object.'); } if (options && typeof options === 'object') { options.uri = uri; } else if (typeof uri === 'string') { options = {uri: uri}; } else { options = uri; } options = copy(options); if (options.url && !options.uri) { options.uri = options.url; delete options.url; } // 2 - check types type('uri', options.uri, 'String|Object'); type('options.method', options.method, 'String?'); type('options.qs', options.qs, 'Object?'); type('options.headers', options.headers, 'Object?'); if (options.body !== undefined && !Buffer.isBuffer(options.body)) { type('options.body', options.body, 'String|Buffer'); } type('options.auth', options.auth, 'Object?'); // 3 - normalize types if (typeof options.uri === 'string') { options.uri = url.parse(options.uri); } options.method = (options.method || 'GET').toUpperCase(); if (options.qs) { var baseQs = qs.parse(options.uri.query); for (var i in options.qs) { baseQs[i] = options.qs[i]; } if (qs.stringify(baseQs) !== '') { options.uri = url.parse(options.uri.href.split('?')[0] + '?' + qs.stringify(baseQs)); } } options.headers = options.headers || {}; if (typeof options.body === 'string') { options.body = new Buffer(options.body); } if (!options.body) { options.body = new Buffer(0); } if (options.auth) { if (hasOwnProperty.call(options.auth, 'username')) options.auth.user = options.auth.username; if (hasOwnProperty.call(options.auth, 'password')) options.auth.pass = options.auth.password; } else if (options.uri.auth) { var authPieces = options.uri.auth.split(':').map(function(item){ return qs.unescape(item); }); options.auth = { user: authPieces[0], pass: authPieces.slice(1).join(':') }; } if (options.auth) { var authHeader = options.auth.pass === undefined ? options.auth.user : options.auth.user + ':' + options.auth.pass; options.headers['Authorization'] = 'Basic ' + toBase64(authHeader); } for (var key in options.headers) { type('options.headers[' + key + ']', options.headers[key], 'String'); if (options.headers[key] === '') { delete options.headers[key]; } } if (module.exports.native && !options.headers['Content-Type']) { options.headers['Content-Type'] = ''; } if (module.exports.native && !options.headers['Accept']) { options.headers['Accept'] = ''; } var request = new Request(options.uri, options.method, options.headers, options.body); var req = module.exports.httpSync.request({ protocol: request.uri.protocol.replace(/\:$/, ''), host: request.uri.hostname, port: request.uri.port, path: request.uri.path, method: request.method, headers: request.headers, body: request.body }); req._headers = request.headers; var res = req.end(); if (options.encoding !== null) { res.body = res.body.toString(options.encoding); } return new Response(res.statusCode, res.headers, res.body); }
request(requestOptions, function (error, response, body) { var data; try { data = JSON.parse(body); } catch (e) { return !!onError ? onError(e) : debug('got an error on ' + method + ' request for:\n' + path + '\n' + 'with query:\n' + qs.stringify(query) + '\n' + 'Error payload:\n' + util.inspect(body)); } if (error) return !!onError ? onError(error) : debug('got an error on ' + method + ' request for:\n' + path + '\n' + 'with query:\n' + qs.stringify(query) + '\n' + 'Error payload:\n' + util.inspect(error)); if (!error && response.statusCode != 200) return !!onError ? onError(data) : debug('got an error on ' + method + ' request for:\n' + path + '\n' + 'with query:\n' + qs.stringify(query) + '\n' + 'Error payload:\n' + util.inspect('unexpected status code: ' + response.statusCode)); !!onSuccess ? onSuccess(data) : debug(util.inspect(data)); });
function requestAPI (config, options, callback) { callback = once(callback) options.qs = options.qs || {} if (Array.isArray(options.files)) { options.qs.recursive = true } if (Array.isArray(options.path)) { options.path = options.path.join('/') } if (options.args && !Array.isArray(options.args)) { options.args = [options.args] } if (options.args) { options.qs.arg = options.args } if (options.files && !Array.isArray(options.files)) { options.files = [options.files] } if (options.progress) { options.qs.progress = true } if (options.qs.r) { options.qs.recursive = options.qs.r // From IPFS 0.4.0, it throws an error when both r and recursive are passed delete options.qs.r } options.qs['stream-channels'] = true let stream if (options.files) { stream = getFilesStream(options.files, options.qs) } // this option is only used internally, not passed to daemon delete options.qs.followSymlinks const method = 'POST' const headers = {} if (isNode) { // Browsers do not allow you to modify the user agent headers['User-Agent'] = config['user-agent'] } if (options.files) { if (!stream.boundary) { return callback(new Error('No boundary in multipart stream')) } headers['Content-Type'] = `multipart/form-data; boundary=${stream.boundary}` } const qs = Qs.stringify(options.qs, { arrayFormat: 'repeat', encoder: data => { // TODO: future releases of qs will provide the default // encoder as a 2nd argument to this function; it will // no longer be necessary to import qsDefaultEncoder if (Buffer.isBuffer(data)) { let uriEncoded = '' for (const byte of data) { // https://tools.ietf.org/html/rfc3986#page-14 // ALPHA (%41-%5A and %61-%7A), DIGIT (%30-%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) if ( (byte >= 0x41 && byte <= 0x5A) || (byte >= 0x61 && byte <= 0x7A) || (byte >= 0x30 && byte <= 0x39) || (byte === 0x2D) || (byte === 0x2E) || (byte === 0x5F) || (byte === 0x7E) ) { uriEncoded += String.fromCharCode(byte) } else { const hex = byte.toString(16) // String.prototype.padStart() not widely supported yet const padded = hex.length === 1 ? `0${hex}` : hex uriEncoded += `%${padded}` } } return uriEncoded } return qsDefaultEncoder(data) } }) const req = request(config.protocol)({ hostname: config.host, path: `${config['api-path']}${options.path}?${qs}`, port: config.port, method: method, headers: headers, protocol: `${config.protocol}:` }, onRes(options.buffer, callback)) req.on('error', (err) => { callback(err) }) if (options.files) { stream.pipe(req) } else { req.end() } return req }
module.exports = function (method, model, options) { var type = methodMap[method]; var headers = {}; // Default options, unless specified. _.defaults(options || (options = {}), { emulateHTTP: false, emulateJSON: false, // overrideable primarily to enable testing xhrImplementation: xhr }); // Default request options. var params = {type: type}; // Ensure that we have a URL. if (!options.url) { options.url = _.result(model, 'url') || urlError(); } // Ensure that we have the appropriate request data. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { params.json = options.attrs || model.toJSON(options); } // If passed a data param, we add it to the URL or body depending on request type if (options.data && type === 'GET') { // make sure we've got a '?' options.url += _.contains(options.url, '?') ? '&' : '?'; options.url += qs.stringify(options.data); } // For older servers, emulate JSON by encoding the request into an HTML-form. if (options.emulateJSON) { headers['Content-Type'] = 'application/x-www-form-urlencoded'; params.body = params.json ? {model: params.json} : {}; delete params.json; } // For older servers, emulate HTTP by mimicking the HTTP method with `_method` // And an `X-HTTP-Method-Override` header. if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { params.type = 'POST'; if (options.emulateJSON) params.body._method = type; headers['X-HTTP-Method-Override'] = type; } // When emulating JSON, we turn the body into a querystring. // We do this later to let the emulateHTTP run its course. if (options.emulateJSON) { params.body = qs.stringify(params.body); } // Start setting ajaxConfig options (headers, xhrFields). var ajaxConfig = (_.result(model, 'ajaxConfig') || {}); // Combine generated headers with user's headers. if (ajaxConfig.headers) { _.extend(headers, ajaxConfig.headers); } params.headers = headers; //Set XDR for cross domain in IE8/9 if (ajaxConfig.useXDR) { params.useXDR = true; } // Set raw xhr options. if (ajaxConfig.xhrFields) { var beforeSend = ajaxConfig.beforeSend; params.beforeSend = function (req) { for (var key in ajaxConfig.xhrFields) { req[key] = ajaxConfig.xhrFields[key]; } if (beforeSend) return beforeSend.apply(this, arguments); }; params.xhrFields = ajaxConfig.xhrFields; } else { params.beforeSend = ajaxConfig.beforeSend; } // Turn a jQuery.ajax formatted request into xhr compatible params.method = params.type; var ajaxSettings = _.extend(params, options); // Make the request. The callback executes functions that are compatible // With jQuery.ajax's syntax. var request = options.xhr = options.xhrImplementation(ajaxSettings, function (err, resp, body) { if (err && options.error) return options.error(resp, 'error', err.message); // Parse body as JSON if a string. if (body && typeof body === 'string') { try { body = JSON.parse(body); } catch (err) { if (options.error) return options.error(resp, 'error', err.message); } } if (options.success) return options.success(body, 'success', resp); }); model.trigger('request', model, request, options, ajaxSettings); request.ajaxSettings = ajaxSettings; return request; };
dataSource: this.state.dataSource.cloneWithRows(this.buildRowsFromResults([])) }); } } else { this._disableRowLoaders(); console.warn('google places autocomplete: ' + responseJSON.status); } } else { this._disableRowLoaders(); console.warn('google places autocomplete: request could not be completed or has been aborted'); } }; request.open('GET', 'https://maps.googleapis.com/maps/api/place/details/json?' + Qs.stringify({ key: this.props.query.key, placeid: rowData.place_id, language: this.props.query.language, })); request.send(); } else if (rowData.isCurrentLocation === true) { if (this.state.currentLocationClicked){ this.setState({ currentLocationClicked: false, text: "" }) this.props.onPress({"description": ""}); }else{ this.setState({ currentLocationClicked: true }) // display loader
server.on('request', function (req, res) { res.writeHead(500) res.end(qs.stringify({error: 'invalid'})) })
form.parse(obj, function (err, originalFields/* , files*/) { if (err) { throw err; } var parsedFields = querystring.parse(querystring.stringify(originalFields)); f.handle(parsedFields, callbacks); });
grunt.registerMultiTask('php2html', 'Generate HTML from PHP', function() { var cb = this.async(), targetDirectory, queryString = '', options = this.options({ processLinks: true, process: false, htmlhint: undefined, docroot: undefined, serverPort: 8888 }); // nothing to do if (this.files.length < 1) { grunt.log.warn('Destination not written because no source files were provided.'); return; } // read config file for htmlhint if available if (options.htmlhintrc) { if (options.htmlhintrc === true) { options.htmlhintrc = findFile('.htmlhintrc',process.cwd()); } try { var rc = grunt.file.readJSON(options.htmlhintrc); grunt.util._.defaults(options.htmlhint, rc); } catch (err) { grunt.log.error('.htmlhintrc not found!'); } delete options.htmlhintrc; } // set to undefined to use default params when value is true if (options.htmlhint === true) { options.htmlhint = undefined; } // set empty object to false to keep backwards compatibility if (_.isObject(options.htmlhint) && Object.keys(options.htmlhint).length ===0) { options.htmlhint = false; } // $_GET data if (typeof options.getData !== 'undefined') { queryString = qs.stringify(options.getData); } // Loop files array grunt.util.async.forEachSeries(this.files, function(f, nextFileObj) { // try to get docroot // first: docroot from options // third: use process cwd var docroot = path.normalize(options.docroot || f.orig.cwd || process.cwd()); // check docroot if (!grunt.file.exists(docroot)) { grunt.log.warn('Docroot "' + docroot + '" does not exist'); return nextFileObj(); } // absolutize docroot if (!grunt.file.isPathAbsolute(docroot)) { docroot = path.normalize(path.join(process.cwd(), docroot)); } // remove trailing slash docroot = docroot.replace(/\/$/, ''); // Warn on and remove invalid source files (if nnull was set). var files = f.src.filter(function(filepath) { if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { return true; } }); // check files if (files.length === 0) { grunt.log.warn('Destination not written because no source files were found.'); // No src files, goto next target. Warn would have been issued above. return nextFileObj(); } // check if dest is directory if (detectDestType(f.dest) === 'directory') { targetDirectory = path.normalize(f.dest); } else { targetDirectory = path.dirname(f.dest); } // make shure dest directory exists if (!grunt.file.isDir(targetDirectory)) { grunt.file.mkdir(targetDirectory); } grunt.util.async.concatSeries(files, function(file, next) { var target, uri = computeUri(docroot, file); // check if uri exists if (!grunt.file.exists(path.join(docroot, uri))) { grunt.log.warn('Source file not found: ', uri); return; } // compute target filename if (detectDestType(f.dest) === 'directory') { target = path.join(targetDirectory, path.basename(uri, '.php') + '.html'); } else { target = path.join(targetDirectory, path.basename(f.dest)); } grunt.log.debug('----------------------------------'); grunt.log.debug('docroot: ', docroot); grunt.log.debug('uri', uri); grunt.log.debug('target', target); grunt.log.debug('----------------------------------'); // start server middleware = gateway(docroot, { '.php': 'php-cgi' }); // start server with php middleware app = http.createServer(function(req, res) { // Pass the request to gateway middleware middleware(req, res, function(err) { grunt.log.warn(err); res.writeHead(204, err); res.end(); }); }); grunt.log.write('Processing ' + file + '...'); compilePhp(options.serverPort, uri, queryString, function(response, err) { // replace relative php links with corresponding html link if (response && options.processLinks) { _.forEach(response.match(/href=['"]([^'"]+\.php(?:\?[^'"]*)?)['"]/gm), function(link) { if (link.match(/:\/\//)) { return; } var hlink = link.replace(/(\w)\.php([^\w])/g, '$1.html$2'); response = response.replace(link, hlink); }); } // doeas the last part of the job var finish = function(target, response, cb) { var messages = [], empty = typeof response === 'undefined' || response === ''; // Lint generated html and check if response is empty if (options.htmlhint !== false) { messages = HTMLHint.verify(response || '', options.htmlhint); } // move on to the next file if everything went right if (!err && messages.length === 0 && !empty) { grunt.file.write(target, response); grunt.log.ok(); grunt.log.debug(target + ' written'); compiled.push(target); // there was an error, show messages to the user if applicable and move on } else { grunt.log.error(); if (empty) { grunt.log.warn('Resulting HTML is empty'); } // output messages messages.forEach(function(message) { grunt.log.writeln("[".red + ( "L" + message.line ).yellow + ":".red + ( "C" + message.col ).yellow + "]".red + ' ' + message.message.yellow); var evidence = message.evidence, col = message.col; if (col === 0) { evidence = '?'.inverse.red + evidence; } else if (col > evidence.length) { evidence = evidence + ' '.inverse.red; } else { evidence = evidence.slice(0, col - 1) + evidence[col - 1].inverse.red + evidence.slice(col); } }); } cb(); }; // processOutput function if (options.process && typeof options.process === 'function') { options.process(response, function callback(modified) { finish(target, modified, next); }); } else { finish(target, response, next); } }); }, function() { grunt.log.debug('done'); nextFileObj(); }); }, cb); });
function setupServerMock(client, provider, servers) { if (provider === 'digitalocean') { var account = require(__dirname + '/../../configs/mock/digitalocean'); servers.server .get('/droplets/new?' + qs.stringify({ name: 'create-test-setWait', region_id: 1, size_id: 66, image_id: 1601, client_id: account.clientId, api_key: account.apiKey })) .replyWithFile(200, __dirname + '/../../fixtures/digitalocean/create-server.json') .get('/droplets/354526?' + qs.stringify({ client_id: account.clientId, api_key: account.apiKey })) .replyWithFile(200, __dirname + '/../../fixtures/digitalocean/not-active.json') .get('/droplets/354526?' + qs.stringify({ client_id: account.clientId, api_key: account.apiKey })) .replyWithFile(200, __dirname + '/../../fixtures/digitalocean/active.json'); } else if (provider === 'rackspace') { servers.server .post('/v2/123456/servers', { server: { name: 'create-test-setWait', flavorRef: 2, imageRef: '9922a7c7-5a42-4a56-bc6a-93f857ae2346', personality: [], key_name: null } }, {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(202, __dirname + '/../../fixtures/rackspace/setWaitResp1.json') .get('/v2/123456/servers/a0a5f183-b94e-4a41-a854-64cff53375bf', {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(200, __dirname + '/../../fixtures/rackspace/a0a5f183-b94e-4a41-a854-64cff53375bf.json'); } else if (provider === 'openstack') { servers.server .post('/v2/72e90ecb69c44d0296072ea39e537041/servers', { server: { name: 'create-test-setWait', flavorRef: 1, imageRef: '506d077e-66bf-44ff-907a-588c5c79fa66', personality: [], key_name: null } }, {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(202, __dirname + '/../../fixtures/openstack/creatingServer.json') .get('/v2/72e90ecb69c44d0296072ea39e537041/servers/5a023de8-957b-4822-ad84-8c7a9ef83c07', {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(200, __dirname + '/../../fixtures/openstack/serverCreated.json'); } else if (provider === 'joyent') { servers.server .post('/' + client.account + '/machines', { name: 'create-test-setWait', 'package': 'Small 1GB', dataset: 'sdc:sdc:nodejitsu:1.0.0' }, {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(200, __dirname + '/../../fixtures/joyent/setWait.json') .get('/' + client.account + '/machines/534aa63a-104f-4d6d-a3b1-c0d341a20a53', {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(200, __dirname + '/../../fixtures/joyent/setWaitResp1.json'); } else if (provider === 'amazon') { servers.server .filteringRequestBody(helpers.authFilter) .post('/?Action=RunInstances', { 'ImageId': 'ami-85db1cec', 'InstanceType': 'm1.small', 'MaxCount': '1', 'MinCount': '1', 'UserData': 'eyJuYW1lIjoiY3JlYXRlLXRlc3Qtc2V0V2FpdCJ9' }, {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(200, __dirname + '/../../fixtures/amazon/run-instances.xml') .post('/?Action=DescribeInstances', { 'Filter.1.Name': 'instance-state-code', 'Filter.1.Value.1': '0', 'Filter.1.Value.2': '16', 'Filter.1.Value.3': '32', 'Filter.1.Value.4': '64', 'Filter.1.Value.5': '80', 'InstanceId.1': 'i-1d48637b' }, {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(200, __dirname + '/../../fixtures/amazon/pending-server.xml') .post('/?Action=DescribeInstanceAttribute', { 'Attribute': 'userData', 'InstanceId': 'i-1d48637b' }, {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(200, __dirname + '/../../fixtures/amazon/running-server-attr.xml') .post('/?Action=DescribeInstances', { 'Filter.1.Name': 'instance-state-code', 'Filter.1.Value.1': '0', 'Filter.1.Value.2': '16', 'Filter.1.Value.3': '32', 'Filter.1.Value.4': '64', 'Filter.1.Value.5': '80', 'InstanceId.1': 'i-1d48637b' }, {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(200, __dirname + '/../../fixtures/amazon/running-server.xml') .post('/?Action=DescribeInstanceAttribute', { 'Attribute': 'userData', 'InstanceId': 'i-1d48637b' }, {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(200, __dirname + '/../../fixtures/amazon/running-server-attr.xml'); } else if (provider === 'azure') { servers.server .get('/azure-account-subscription-id/services/hostedservices/create-test-setWait?embed-detail=true', {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(404, __dirname + '/../../fixtures/azure/hosted-service-404.xml') .post('/azure-account-subscription-id/services/hostedservices', helpers.loadFixture('azure/create-hosted-service.xml'), {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .reply(201, '', { location: 'https://management.core.windows.net/subscriptions/azure-account-subscription-id/compute/create-test-setWait', 'x-ms-request-id': 'b67cc525ecc546618fd6fb3e57d724f5'}) .get('/azure-account-subscription-id/operations/b67cc525ecc546618fd6fb3e57d724f5', {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(200, __dirname + '/../../fixtures/azure/operation-succeeded.xml') .get('/azure-account-subscription-id/services/images/CANONICAL__Canonical-Ubuntu-12-04-amd64-server-20120528.1.3-en-us-30GB.vhd', {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(200, __dirname + '/../../fixtures/azure/image-1.xml') .post('/azure-account-subscription-id/services/hostedservices/create-test-setWait/deployments', helpers.loadFixture('azure/create-deployment.xml'), {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .reply(202, '', {'x-ms-request-id': 'b67cc525ecc546618fd6fb3e57d724f5'}) .get('/azure-account-subscription-id/operations/b67cc525ecc546618fd6fb3e57d724f5', {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(200, __dirname + '/../../fixtures/azure/operation-inprogress.xml') .get('/azure-account-subscription-id/operations/b67cc525ecc546618fd6fb3e57d724f5', {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(200, __dirname + '/../../fixtures/azure/operation-succeeded.xml') // TODO: have to do this twice as setWait() does not check server status before calling server.refresh()? .get('/azure-account-subscription-id/services/hostedservices/create-test-setWait?embed-detail=true', {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(200, __dirname + '/../../fixtures/azure/running-server.xml') .get('/azure-account-subscription-id/services/hostedservices/create-test-setWait?embed-detail=true', {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(200, __dirname + '/../../fixtures/azure/running-server.xml') .filteringRequestBodyRegEx(/.*/, '*') .post('/azure-account-subscription-id/services/hostedservices/create-test-setWait/certificates', '*', {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .reply(202, '', {'x-ms-request-id': 'b67cc525ecc546618fd6fb3e57d724f5'}) .get('/azure-account-subscription-id/operations/b67cc525ecc546618fd6fb3e57d724f5', {'User-Agent': utile.format('nodejs-pkgcloud/%s', pkgcloud.version)}) .replyWithFile(200, __dirname + '/../../fixtures/azure/operation-succeeded.xml'); } }
function Request(uri, options) { events.EventEmitter.call(this); this.url = url.parse(uri); this.options = options; this.headers = { 'Accept': '*/*', 'User-Agent': 'Restler for node.js', 'Host': this.url.host }; this.headers['Accept-Encoding'] = 'gzip, deflate'; mixin(this.headers, options.headers || {}); // set port and method defaults if (!this.url.port) this.url.port = (this.url.protocol == 'https:') ? '443' : '80'; if (!this.options.method) this.options.method = (this.options.data) ? 'POST' : 'GET'; if (typeof this.options.followRedirects == 'undefined') this.options.followRedirects = true; // stringify query given in options of not given in URL if (this.options.query && !this.url.query) { if (typeof this.options.query == 'object') this.url.query = qs.stringify(this.options.query); else this.url.query = this.options.query; } this._applyAuth(); if (this.options.multipart) { this.headers['Content-Type'] = 'multipart/form-data; boundary=' + multipart.defaultBoundary; var multipart_size = multipart.sizeOf(this.options.data, multipart.defaultBoundary); if (typeof multipart_size === 'number' && multipart_size === multipart_size) { this.headers['Content-Length'] = multipart_size; } else { console.log("Building multipart request without Content-Length header, please specify all file sizes"); } } else { if (typeof this.options.data == 'object' && !Buffer.isBuffer(this.options.data)) { this.options.data = qs.stringify(this.options.data); this.headers['Content-Type'] = 'application/x-www-form-urlencoded'; this.headers['Content-Length'] = this.options.data.length; } if (typeof this.options.data == 'string') { var buffer = new Buffer(this.options.data, this.options.encoding || 'utf8'); this.options.data = buffer; this.headers['Content-Length'] = buffer.length; } if (!this.options.data) { this.headers['Content-Length'] = 0; } } var proto = (this.url.protocol == 'https:') ? https : http; var finalOptions = { host: this.url.hostname, port: this.url.port, path: this._fullPath(), method: this.options.method, headers: this.headers, rejectUnauthorized: this.options.rejectUnauthorized }; if (this.url.protocol == 'https:' && this.options.key && this.options.cert) { finalOptions.key = this.options.key; finalOptions.cert = this.options.cert; } this.request = proto.request(finalOptions); this._makeRequest(); }
export function loadConversations(query) { const conversationsQuery = qs.stringify(query); return request.get(`${apiUrl}/conversations?${conversationsQuery}`); }
function setUpLoggedInRoute( req, res, next ) { var redirectUrl, protocol, start, context; res.set( { 'X-Frame-Options': 'SAMEORIGIN' } ); context = getDefaultContext( req ); if ( config( 'wpcom_user_bootstrap' ) ) { const user = require( 'user-bootstrap' ); protocol = req.get( 'X-Forwarded-Proto' ) === 'https' ? 'https' : 'http'; redirectUrl = config( 'login_url' ) + '?' + qs.stringify( { redirect_to: protocol + '://' + config( 'hostname' ) + req.originalUrl } ); // if we don't have a wordpress cookie, we know the user needs to // authenticate if ( ! req.cookies.wordpress_logged_in ) { debug( 'User not logged in. Redirecting to %s', redirectUrl ); res.redirect( redirectUrl ); return; } start = new Date().getTime(); debug( 'Issuing API call to fetch user object' ); user( req.get( 'Cookie' ), function( error, data ) { var end, searchParam, errorMessage; if ( error ) { if ( error.error === 'authorization_required' ) { debug( 'User public API authorization required. Redirecting to %s', redirectUrl ); res.redirect( redirectUrl ); } else { if ( error.error ) { errorMessage = error.error + ' ' + error.message; } else { errorMessage = error.message; } console.log( 'API Error: ' + errorMessage ); res.status( 500 ).render( '500.jade', context ); } return; } end = ( new Date().getTime() ) - start; debug( 'Rendering with bootstrapped user object. Fetched in %d ms', end ); context.user = data; context.isRTL = data.isRTL ? true : false; if ( data.localeSlug ) { context.lang = data.localeSlug; } if ( req.path === '/' && req.query ) { searchParam = req.query.s || req.query.q; if ( searchParam ) { res.redirect( 'https://' + context.lang + '.search.wordpress.com/?q=' + encodeURIComponent( searchParam ) ); return; } if ( req.query.newuseremail ) { debug( 'Detected legacy email verification action. Redirecting...' ); res.redirect( 'https://wordpress.com/verify-email/?' + qs.stringify( req.query ) ); return; } if ( req.query.action === 'wpcom-invite-users' ) { debug( 'Detected legacy invite acceptance action. Redirecting...' ); res.redirect( 'https://wordpress.com/accept-invite/?' + qs.stringify( req.query ) ); return; } } req.context = context; next(); } ); } else { req.context = context; next(); } }
export async function queryRule(params) { return request(`/api/rule?${stringify(params)}`); }
export const userRegister = params => { return axios.post('/user/v1.0/register', qs.stringify(params)).then(res => res.data); };
export async function queryFakeList(params) { return request(`/api/fake_list?${stringify(params)}`); }
export const updatePassword = params => { return axios.post('/user/v1.0/update_password', qs.stringify(params)).then(res => res.data); };
axios.defaults.paramsSerializer = params => qs.stringify( params, { arrayFormat: 'brackets' });
Twitter.prototype.buildQS = function (params) { if (params && Object.keys(params).length > 0) { return '?' + qs.stringify(params); } return ''; };
articleCardListOnChange = (page, pageSize) => { const { history } = this.props; // replace pagination data to history history.replace({ search: qs.stringify({ page, pageSize }) }); };
function stringifyQuery(params) { return qs.stringify(params, { arrayFormat: 'indices' }) }
session.set = function(key, value) { _session[key] = value; jar.set(cookie, qs.stringify(_session), options); }