this[method] = (path, { params, data } = {}) => new Promise((resolve, reject) => { const request = superagent[method](formatUrl(path)); // if (cookie.load('token')) { // this.token = cookie.load('token'); // } if (params) { request.query(params); } /* if (__SERVER__ && req.get('cookie')) { request.set('cookie', req.get('cookie')); } if (this.token !== null) { request.set('Authorization', this.token); } */ if (data) { request.send(data); } request.withCredentials().end((err, { body } = {}) => { if (err) { reject(body || err); } return resolve(body); }); });
/** * Send Request * * @param {string} method - request method * @param {string} path - url path * @param {APIOption} options - options * @return {Promise<Object, Error>} */ send(method: string, path: string, options: APIOption = {}): Promise<APIResponse> { const defaultOptions = this.getDefaultOptions(); const headers = Object.assign( {Accept: 'application/json'}, defaultOptions.headers || {}, options.headers || {} ); const data = Object.assign({}, defaultOptions.data || {}, options.data || {}); const query = Object.assign({}, defaultOptions.query || {}, options.query || {}); let req = request[method](`${this.endpoint}${path}`); Object.keys(headers).forEach(key => { req = req.set(key, headers[key]); }); if (Object.keys(query).length) { req = req.query(query); } if (Object.keys(data).length) { req = req.send(data); } if (this.timeout) { req = req.timeout(this.timeout); } return new Promise((resolve, reject) => { req.end((err, res) => { const response = this.toResponse(err, res); if (err) { return reject(response); } return resolve(response); }); }); }
store.findAll = function(query, cb) { var Model = this; var opts = Model.options; var url = urlForAction('index', opts, query); var method = opts.ajax.actions.index.method; var req = request[method](url).set(opts.ajax.header); if (typeof query == 'object' && Object.keys(query).length) { req.query(qs.stringify(query)); } Model.emit('ajax request', req); req.end(function(err, res) { Model.emit('ajax response', res); err = errorForRes(Model, err, req, res, cb); if (res && typeof res.body === 'object' && res.body.length) { for (var i=0, l=res.body.length; i<l; i++) { res.body[i] = Model.create(res.body[i]); } } cb(err, res ? res.body : res); }); };
return new Promise((resolve, reject) => { let s = superagent[method](path).timeout(this.config.timeout || 5000); if (s.redirects) { s.redirects(0); } s.query(query); s.set(this.buildAuthHeader()); s.set(this.buildHeaders()); if (query.id && !Array.isArray(query.id)) { delete query.id; } s.end((err, res) => { if (err && err.timeout) { err.status = 504; } const origin = this.origin; const path = this.path(method, query); const fakeReq = { origin, path, method, query }; const req = res ? res.request : fakeReq; handle(resolve, reject)(err, res, req, originalMethod); }); });
this[method] = (path, { params, data, attach, field } = {}) => new Promise((resolve, reject) => { const request = superagent[method](formatUrl(path)); if (params) { request.query(params); } if (__SERVER__ && req.get('cookie')) { request.set('cookie', req.get('cookie')); } if (data) { request.send(data); } if (attach) { attach.foreach(item => request.attach(item.key, item.value)); } if (field) { field.forEach(item => request.field(item.key, item.value)); } request.end((err, { body } = {}) => err ? reject(body || err) : resolve(body)); }));
return when.promise(function (resolve, reject) { var req = request[method](path.join("/api", self.base, pathname)); if (data) { req.send(data); } req.set("Authorization", AdminStore.getState().password); req.end(function (err, res) { switch (res.body.status) { case "success": resolve(res.body.data); break; case "error": case "fail": err = new Error(res.body.message); err.data = res.body.data; if (res.body.code === 401) { Dispatcher.dispatch(Constants.API_ERROR_UNAUTHORISED); } reject(err); break; default: reject(new Error(err || "Unknown Error")); break; } }); });
export default store => next => action => { if ( ! action[CALL_API] ) { return next(action); } let request = action[CALL_API]; let { getState } = store; let deferred = Promise.defer(); let { method, url, successType } = request; superAgent[method](url) .end((err, res)=> { if ( !err ) { next({ type: successType, response: res.body }); if (_.isFunction(request.afterSuccess)) { request.afterSuccess({ getState }); } } deferred.resolve(); }); return deferred.promise; };
this[method] = (path, { params, data, headers, files, fields } = {}) => new Promise((resolve, reject) => { const request = superagent[method](formatUrl(path)); if (params) { request.query(params); } if (__SERVER__ && req.get('cookie')) { request.set('cookie', req.get('cookie')); } if (headers) { request.set(headers); } if (this.token) { request.set('Authorization', `Bearer ${this.token}`); } if (files) { files.forEach(file => request.attach(file.key, file.value)); } if (fields) { fields.forEach(item => request.field(item.key, item.value)); } if (data) { request.send(data); } request.end((err, { body } = {}) => (err ? reject(body || err) : resolve(body))); });
new Promise((resolve, reject) => { const url = `${process.env.API_ENDPOINT}/${path}` const request = superagent[method](url) request.set('Accept', 'application/json') if (method === 'post') { request.set('Content-Type', 'application/json') } if (params) { request.query(params) } if (data) { request.send(data) } if (headers) { _.forOwn(headers, (val, key) => request.set(key, val)) } request.end((err, { body } = {}) => { if (err) { return reject(body || err) } return resolve(body) }) })
User.get(req.claims.sub, function (err, user) { if (err) { return next(err) } if (!user) { return next(new InvalidRequestError('Unknown user')) } if (!user.providers[req.params.provider]) { return next(new InvalidRequestError('No provider for this user')) } var auth = user.providers[req.params.provider].auth var url = endpoint.url var method = endpoint.method.toLowerCase() var param = endpoint.auth && endpoint.auth.param var token = auth && auth.access_token request[method](url) .query(param + '=' + token) .end(function (err, response) { res.json({ err: err, response: response }) }) })
export default store => next => action => { if ( ! action[CALL_API] ) { return next(action); } let request = action[CALL_API]; let { method, authToken, path, query, failureType, successType, sendingType } = request; let { dispatch } = store; dispatch({ type: sendingType }); let call = superAgent[method](path); if(authToken != null) { call.set('x-access-token', authToken); } call.send(query) .end((err, res)=> { if (err) { dispatch({ type: failureType, response: err }); } else { dispatch({ type: successType, response: res.body }); } }); };
return new Promise((resolve, reject) => { let req = superagent[method](path).send(body); req.end((err, res) => { if (err) return reject(err); return resolve(res); }); });
function requestBookId (method, bookizArc, bookrc, token = bookizArc.token) { if (token === undefined) { console.log(chalk.red('Cannot proceed without API_token')) return } const url = bookizArc.urls.baseURL request[method](url) .send() .set('Accept', 'application/json') .set('Accept', 'application/bookiza.bubblin.v2') .set('Authorization', `Token token=${token}`) .end((err, res) => { if (!err && res.ok && res.body.status === 201 && res.body.id !== null) { bookrc.book_id = res.body.id fs.writeFileSync('.bookrc', JSON.stringify(bookrc, null, 2)) pushBook(bookizArc, bookrc) } else { let errorMessage if (res && res.body.status === 401) { errorMessage = 'Authentication failed! Bad username/password?' } else if (res.body.status === 403) { errorMessage = 'Submission unauthorized!' } else { errorMessage = res.text } console.error(chalk.red(errorMessage)) process.exit(1) } }) }
return new Promise(function (resolve, reject) { var method = settings.method.toLowerCase(); var req = request[method](settings.url); for (var name in settings.headers) { req = req.set(name, settings.headers[name]); } if (typeof settings.data === 'object') { req = req.send(settings.data); } req.end(function (err, res) { if (err) { reject(err); return; } if (res.header['content-type'] && res.header['content-type'].substr(0, 5) === 'text/') { return resolve(res.text); } resolve(res.body); }); });
this[method] = (path, { params, data } = {}) => new Promise((resolve, reject) => { const request = superagent[method](formatUrl(path)); if (params) { request.query(params); } console.log('access:' + path); // if (__SERVER__ && req.get('cookie')) { // request.set('cookie', req.get('cookie')); // } if (cookie && cookie.load('token')) { console.log('cookie:' + cookie.load('token')); request.set('authorization', 'Bearer ' + cookie.load('token')); } if (data) { request.send(data); } request.end((err, { status, headers, body } = {}) => { // console.log(status); // if (status === 401) { // window.location.pathname = '/login'; // } if (headers && headers.authorization) { // console.log('has refresh'); // console.log(headers.authorization); cookie.save('token', headers.authorization); } return err ? reject(status, body) : resolve(body); }); }));
this[method] = (path, { params, data, attach } = {}) => new Promise((resolve, reject) => { const request = superagent[method](formatUrl(path)); if (params) { request.query(params); } if (attach) { for (const [fieldName, file] of Object.entries(attach)) { request.attach(fieldName, file); } } if (__SERVER__ && req.get('cookie')) { request.set('cookie', req.get('cookie')); } if (data) { request.send(data); } request.end((err, { body, headers } = {}) => { if (headers && headers['x-remove-user-token'] === 'yes') { const { dispatch } = this.store; dispatch(clearToken()); dispatch(setUser()); dispatch(showToast('Время сессии истекло - необходимо войти снова', 'cancel', 'error')); } return err ? reject(body || err) : resolve(body); }); }));
export default store => next => action => { const {request, type, payload={}, interrupt} = action; if (type !== REQUEST_API) { return next(action); } if (isFunction(interrupt) && interrupt(store)) { return next(action); } const {backendHost, token}= store.getState().config; const {url, headers={}, method='get', params} = request; const {start, success, fail} = request.actions; const sendType = method === 'get' ? 'query' : 'send'; dispatchAction(store.dispatch, start, {payload: payload}); const currentRequest = requestAjax[method](backendHost + url) .set('Authorization', token) .set('Accept', 'application/json'); Object .keys(headers) .forEach(key=>currentRequest.set(key, headers[key])); currentRequest[sendType](params) .end((error, response) => { if (error) { dispatchAction(store.dispatch, fail, {error: error}, {payload: payload}); } else { dispatchAction(store.dispatch, success, {response: response.body}, {payload: payload}); } }); };
Requests.prototype.make = function(method, endpoint, payload) { var deferred = Q.defer(); method = method.toLowerCase(); if (method !== 'get' && method !== 'post') { throw new Error('Only GET or POST method allowed'); } var request = superagent[method](this._constructUrl(endpoint)) .set('X-API-Key', this.publicKey) .type('application/json') .accept('json'); if (payload) { if (method === 'get') { request = request.query(payload); } else { request.send(payload); } } request.end(function(err, res) { if (err) { if (err.response) { res = err.response; } else { deferred.reject(err); return; } } if (res.ok) { deferred.resolve(res.body); } else { deferred.reject(res.body || res.text); } }); return deferred.promise; };
setTimeout(() => { var method = test.method.toLowerCase(); if (method === 'delete') { method = 'del'; } var call = request[method]('http://localhost:3000' + test.url.replace('{_id}', _id)); // add cookies if (sessionCookie) { call = call.set('Cookie', sessionCookie); } // add data if (test.method === 'POST' || test.method === 'PUT') { if (test.data) { var type = Object.prototype.toString.call(test.data); if (type === '[object Function]') { call = call.send(test.data(_id)) } else { call = call.send(test.data); } } } call.end((error, response) => { // remember cookies if (response.header['set-cookie']) { sessionCookie = response.header['set-cookie']; } // basic call assertions expect(response.status).to.equal(test.statusCode || 200); // append id to user if (response.body._id) { _id = response.body._id; } // check assertions if (!test.assertions) { return done(); } var type = Object.prototype.toString.call(test.assertions); if (type === '[object Array]') { test.assertions.forEach((assertion) => { expect(response.body[assertion]).to.equal(test.body[assertion]); }); done(); } else if (type === '[object Function]') { test.assertions(response.body, done); } else { done(); } }); }, test.delay);
export default store => next => action => { if ( ! action[CALL_API] ) { return next(action) } let request = action[CALL_API] let { getState } = store let deferred = Promise.defer() // handle 401 and auth here let { method, path, types, params, tags } = request const [ requestType, successType, failureType ] = types const callback = (err, res) => { if ( res && res.text ) { if (res.ok) { next({ type: successType, response: res, tags: tags || [] }) if (isFunction(request.afterSuccess)) { request.afterSuccess({ getState }) } } } else { next({ type: failureType, response: {}, tags: tags || [] }) } deferred.resolve() } if (method === 'get') { superAgent[method](formatUrl(path)).timeout(500) .query(qs.stringify(params)) .end(callback) } else { superAgent[method](formatUrl(path)).timeout(500).send(params) .end(callback) } return deferred.promise }
return new Promise((resolve, reject) => { request[method](url) .send(data) .accept("json") .type("json") .end((err, res) => { if (err) { return reject(err); } return resolve(res); }); });
new Promise((resolve, reject) => { const newPath = path.indexOf('http') >= 0 ? path : URL + path; const request = superagent[method](newPath); if (params) { request.query(params); } request.end((err, { body } = {}) => err ? reject(body || err) : resolve(body)); });
module.exports = (options, callback) => { var method = options.method.toLowerCase(); var url = options.url; var request = superagent[method](url); if (options.query) request.query(options.query) if (method === 'post' && options.body) request.send(options.body) if (options.type) request.type(options.type) if (options.accept) request.accept(options.accept) if (options.headers) request.set(options.headers) return request.end(callback); }
API.prototype._http = function(path, method) { var fullUrl = util.format('%s%s', this.server.url, path); var authorization = util.format('Bearer %s', this.token); method = (method || 'GET').toLowerCase(); var request = require('superagent'); var r = request[method](fullUrl) .set('Authorization', authorization); return r; };
SuperagentHttpClient.prototype.execute = function (obj) { var method = obj.method.toLowerCase(); if (method === 'delete') { method = 'del'; } var headers = obj.headers || {}; var r = request[method](obj.url); var name; for (name in headers) { r.set(name, headers[name]); } if (obj.body) { r.send(obj.body); } r.end(function (err, res) { res = res || { status: 0, headers: {error: 'no response from server'} }; var response = { url: obj.url, method: obj.method, headers: res.headers }; var cb; if (!err && res.error) { err = res.error; } if (err && obj.on && obj.on.error) { response.obj = err; response.status = res ? res.status : 500; response.statusText = res ? res.text : err.message; cb = obj.on.error; } else if (res && obj.on && obj.on.response) { response.obj = (typeof res.body !== 'undefined') ? res.body : res.text; response.status = res.status; response.statusText = res.text; cb = obj.on.response; } response.data = response.statusText; if (cb) { cb(response); } }); };
return new Promise((resolve, reject) => { const request = superAgent[method](formatUrl(path)); params && request.query(params); data && request.send(data); request.end((err, {body} = {}) => { if(err) { reject(err || body); } else { resolve(body); } }) });
ApiClient.prototype[method] = (path, { params, data } = {}, dataType = false) => new Promise((resolve, reject) => { const request = superagent[method](formatUrl(path)); if (params) { request.query(params); } // add x-requested-with header request.set({ 'x-requested-with': 'XMLHttpRequest' }); if (__SERVER__) { if (req.get('cookie')) { request.set('cookie', req.get('cookie')); } /* in order to pass `redir_host` check in wr app we need to set the Host header explicitly, otherwise internal network host is set and request is redirected */ if (process.env.APP_HOST) { request.set({ 'Host': process.env.APP_HOST }); } } if (data) { if(dataType) { request.type(dataType); } request.send(data); } // eslint-disable-next-line no-confusing-arrow request.end((err, response) => { const { body } = response; if (__SERVER__) { // if api sets session cookie, ensure its passed back to browser let cookie = response.get('Set-Cookie'); if (cookie) { if (process.env.SCHEME === "https") { cookie += "; Secure"; } res.set('Set-Cookie', cookie); } } return err || !body || body.hasOwnProperty('error') ? reject(body || err) : resolve(body); }); }));
var promise = new Promise(function (resolve, reject) { var method = options.method.toLowerCase(); // Set methods and attach the body of the request (if this is a POST request). var req = request[method](options.url).send(options.data); // Add request headers. for (var header in headers) { req = req.set(header, headers[header]); } // Add all the given parameters to the querystring. req = req.query(queryParams); // Send the request. req .set('Accept', 'application/json') .end(function (err, res) { if (err) { var response = err.response || {}; var data = response.body || {}; var status = err.status; var error; if (errorFormatter && errorFormatter.hasOwnProperty('name') && errorFormatter.hasOwnProperty('message')) { var name = goToPath(errorFormatter.name, data); var message = goToPath(errorFormatter.message, data); error = new APIError(name, message, status); } else { error = new APIError('APIError', JSON.stringify(data), status); } return reject(error); } // If case conversion is enabled for the body of the response, convert // the properties of the body to the specified case. if (convertCaseRes) { for (var key in res.body) { if (res.body.hasOwnProperty(key)) { res.body[convertCaseRes(key)] = res.body[key]; if (key !== convertCaseRes(key)) { delete res.body[key]; } } } } resolve(res.body); }); });
exports.request = function(method, path){ method = method || 'get'; var url = path || ''; var self = this; if (!isAbsolute(url)) url = this.endpoint + url; this.debug('create request %s', method, url); var req = request[method](url); var end = req.end; if (this.ca) req.ca(this.ca); if (this.timeout) req.timeout(this.timeout); if (this.agent) { req.agent(this.agent); } else if (url.indexOf('http:') === 0) { req.agent(http.globalAgent) } else if (url.indexOf('https:') === 0) { req.agent(https.globalAgent) } req.on('response', this.onresponse.bind(this)); req.set('User-Agent', 'Segment.io/1.0'); // Superagent sets Accept-Encoding: gzip, deflate by default. We don't want // any encoding, since compressing TLS responses with gzip makes them // vulnerable to the CRIME attack. // // There may also be a problem with the Node zlib library using a ton of // memory to decompress messages. req.set('Accept-Encoding', 'identity'); req.redirects(0); req.end = onend; function onend(fn){ fn = fn || noop; self.emit('request', this); self.debug('request %s %j', req.url, req._data); return end.call(this, function(err, res){ if (err) return onerror(err, res, fn); if (res.error) return onerror(res.error, res, fn); res.req = req; return fn(null, res); }); } function onerror(err, res, fn){ if (err.timeout) err.code = 'ECONNABORTED'; return fn(err, res); } return req; };
return new Promise(function (resolve, reject) { request[method](url) .send(data) .set(headers) .end(function (err, res) { if (err) { error(err); return reject(err); } success(res.body); return resolve(res.body); }); });