Commit 0ecde801 by 马玮

fetch clues but not full

parent 5f399561
'use strict';
process.env.NODE_CONFIG_DIR = '../config';
const Promise = require('bluebird');
const fs = require('fs');
const redis = require("redis");
const redis = require('redis');
const config = require('config');
const phantom = require('phantom');
const cheerio = require('cheerio');
var Horseman = require('node-horseman');
const tough = require('tough-cookie');
const request = require('request-promise');
const axios = require('axios');
const rp = require('request-promise');
const Horseman = require('node-horseman');
const axiosCookieJarSupport = require('@3846masa/axios-cookiejar-support');
const Promise = require('bluebird');
const captcha = require('../captcha');
Promise.promisifyAll(redis);
Promise.promisifyAll(fs);
axios.defaults.withCredentials = true;
axiosCookieJarSupport(axios);
class AutoHome {
constructor(params) {
......@@ -21,7 +29,22 @@ class AutoHome {
console.log(params);
}
execute() {
async getCookies() {
try {
const client = await redis.createClient();
const cookies_key = this.name + '_cookies';
let cookies = JSON.parse(await client.getAsync(cookies_key));
await cookies.forEach((cookie) => {
cookie.expires = (new Date()).getTime() + (1000 * 60 * 60);
});
await client.quit();
return cookies;
} catch (e) {
throw e;
}
}
async execute() {
return new Promise((resolve, reject) => {
switch (this.params.task) {
case 'login': {
......@@ -30,38 +53,44 @@ class AutoHome {
break;
}
case 'tryLogin': {
console.log('do login');
console.log('do tryLogin');
this.tryLogin();
break;
}
case 'fetchClues': {
console.log('do fetchClues');
this.fetchClues();
break;
}
}
});
}
async tryLogin() {
try {
const client = await redis.createClient();
const cookies_key = this.name + '_cookies';
const cookies = await client.getAsync(cookies_key);
await client.quit();
console.log(JSON.decode(cookies));
let cookies = await this.getCookies();
const horseman = new Horseman();
const loginoutBtnExists = await
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
.viewport(1920, 1080)
.cookies(cookies)
.open('http://ics.autohome.com.cn/passport/Home/Index')
.screenshot('try.png')
.exists('#loginout');
if (loginoutBtnExists) {
console.log('登录成功');
} else {
console.log('登录失败');
}
await horseman
.open('http://ics.autohome.com.cn/BSS/MyMch/PersonalInfo')
.screenshot('try2.png').close();
} catch (e) {
throw e;
}
const instance = await phantom.create(['--ignore-ssl-errors=yes']);
const page = await instance.createPage();
page.property('viewportSize', {width: 1920, height: 1080});
await page.on('onResourceRequested', function(requestData) {
console.info('Requesting', requestData.url);
});
const status = await page.open('http://ics.autohome.com.cn/passport/Home/Index');
console.log(status);
// data:image/png;base64, + baseTxt
await page.render('m5.png');
await instance.exit();
}
async login() {
......@@ -70,68 +99,154 @@ class AutoHome {
const password = this.params.password;
const horseman = new Horseman();
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
.viewport(1920, 1080)
.on('onResourceRequested', (requestData, networkRequest) => {
console.info('Requesting', requestData.url);
})
.open('http://ics.autohome.com.cn/passport/Home/Index')
.screenshot('m1.png')
.crop('#imgValidCodeDealer', 'm2.png')
.cropBase64('#imgValidCodeDealer', 'PNG')
.then((base64Text) => {
return base64Text;
}).then((base64Text) => {
// const imageFile = 'tmp/' + (new Date) . getTime() + '.gif';
const imageFile = 'm5.png';
const writeStream = fs.createWriteStream(imageFile);
// data:image/png;base64, + base64Text
writeStream.write(base64Text, 'base64');
}).then(() => {
const captchaType = config.get('Dealer')[this.name]['captchaType'];
const captchaText = captcha.decode(captchaType, imageFile);
console.info('imageFile:', imageFile);
console.info('captchaText:', captchaText);
})
// .type('input[name="q"]', 'github')
// .click('[name="btnK"]')
// .keyboardEvent('keypress', 16777221)
// .waitForSelector('div.g')
// .count('div.g')
// .log() // prints out the number of results
.close();
return;
await
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
.viewport(1920, 1080)
.open('http://ics.autohome.com.cn/passport/Home/Index');
horseman.on('onResourceRequested', (requestData, networkRequest) => {
console.info('Requesting', requestData.url);
});
// 验证码存储到磁盘
const imageFile =
await
horseman
.screenshot('m1.png')
.crop('#imgValidCodeDealer', 'captcha1.png')
.cropBase64('#imgValidCodeDealer', 'PNG')
.then((base64Text) => {
// const imageFile = 'tmp/' + (new Date) . getTime() + '.gif';
const imageFile = 'captcha2.png';
const writeStream = fs.createWriteStream(imageFile);
// data:image/png;base64, + base64Text
writeStream.write(base64Text, 'base64');
return imageFile;
});
// 验证码解码
const captchaType = config.get('Dealer')[this.name]['captchaType'];
const captchaText = await captcha.decode(captchaType, imageFile);
console.info('captchaText:', captchaText);
// 填写登录表单
page.evaluate(function(username, password, captchaTxt) {
$('#UserNameDealer').val(username);
$('#PasswordDealer').val(password);
$('#checkCodeDealer').val(captchaTxt);
$('#btnDealer').trigger('click');
}, username, password, captchaText);
page.property('clipRect', { top: 0, left: 0, width: 1920, height: 1080 });
await Promise.delay(2000);
await page.render('m3.png');
const cookies = await page.cookies();
const cookie_key = this.name + '_cookie';
const client = await redis.createClient();
client.set(cookie_key, JSON.stringify(cookies), redis.print);
client.quit();
console.info('cookie保存成功');
// await instance.exit();
await
horseman
.type('input[id="UserNameDealer"]', username)
.type('input[id="PasswordDealer"]', password)
.type('input[id="checkCodeDealer"]', captchaText)
.screenshot('m2.png');
// 提交登录表单
await
horseman
.click('[id="btnDealer"]')
.waitForNextPage({ timeout: 5000 })
.catch(Horseman.TimeoutError, function() {
console.log('超时了');
})
.screenshot('m3.png')
.cookies()
.then(async (cookies) => {
console.log(JSON.stringify(cookies));
const cookie_key = this.name + '_cookies';
const client = await redis.createClient();
client.set(cookie_key, JSON.stringify(cookies), redis.print);
client.quit();
console.info('cookie保存成功');
})
.close();
} catch (e) {
throw e;
}
}
// 抓取线索
async fetchClues() {
const cookies = await this.getCookies();
const cookieJar = new tough.CookieJar();
// console.log(cookies);
const Cookie = tough.Cookie;
cookies.forEach((cookieObj) => {
let cookieStr = cookieObj.name + "=" + cookieObj.value + "; path=" + cookieObj.path + "; domain=" + cookieObj.domain;
cookieJar.setCookieSync(cookieStr, 'http://ics.autohome.com.cn');
// cookieJar.setCookie(request.cookie(), 'http://ics.autohome.com.cn/BSS/MyMch/PersonalInfo');
});
// axios.get('http://ics.autohome.com.cn/Dms/Order/Search', {
// jar: cookieJar, // tough.CookieJar or boolean
// withCredentials: true // If true, send cookie stored in jar
// }).then(res => {
// console.log(res.data);
// const writeStream = fs.createWriteStream('test2.html');
// writeStream.write(JSON.stringify(res.data));
// });
// return;
let rowcount;
let customerIndex = 0;
const params = {};
params.appid = 'dms';
params.orderType = 1;
params.priPub = -1;
params.factoryId = 0;
params.seriesId = 0;
params.specId = 0;
params.areaType = 0;
params.provinceId = -2;
params.cityId = -2;
params.status = -1;
params.startTime = '2017.5.8';
params.endtime = '2017.8.7';
params.pageIndex = 1
params.pageSize = 20;
params.salesid = 0;
params.dealerId = 0;
params.productId = 0;
params.assignDealerId = 0;
const fetchByPage = async () => {
console.log('当前页L:', params.pageIndex);
axios.get('http://ics.autohome.com.cn/Dms/Order/SearchOrderList?', {
params: params,
jar: cookieJar,
withCredentials: true
}).then(async (res) => {
const clues = res.data;
if (!rowcount) {
let rowcount = clues.result.rowcount;
console.log('总数:', rowcount);
}
console.log(rowcount);
for (let clue of clues.result.list) {
customerIndex++;
let $ = cheerio.load(clue.CustomerNameStr);
console.log('客户序号:', customerIndex);
console.log('客户姓名:', $.text());
console.log('客户号码:', clue.CustomerPhoneStr);
console.log('负责销售:', clue.SalesNameStr);
console.log('线索类型:', clue.OrderTypeStr);
console.log('线索状态:', clue.OrderStateStr);
console.log('线索获得时间:', clue.LeadTimeStr);
console.log('上牌地区:', clue.LicenseCityStr);
console.log('线索意向车型:', clue.SpecNameStr);
console.log('===========================================================================');
// await Promise.delay(5000);
}
if (customerIndex < rowcount) {
params.pageIndex++;
await fetchByPage();
}
});
}
fetchByPage(params.pageindex);
}
}
module.exports = AutoHome;
\ No newline at end of file

713 KB | W: | H:

713 KB | W: | H:

m1.png
m1.png
m1.png
m1.png
  • 2-up
  • Swipe
  • Onion skin

4.92 KB | W: | H:

713 KB | W: | H:

m2.png
m2.png
m2.png
m2.png
  • 2-up
  • Swipe
  • Onion skin
m3.png

269 KB

m4.png

104 KB

All packages installed at Sun Aug 06 2017 23:20:43 GMT+0800 (CST)
\ No newline at end of file
All packages installed at Mon Aug 07 2017 19:51:45 GMT+0800 (CST)
\ No newline at end of file
Recently updated (since 2017-07-27)
Today:
→ request@2.81.0 › http-signature@1.1.1 › jsprim@^1.2.2(1.4.1) (00:29:57)
Recently updated (since 2017-07-31)
2017-08-03
→ @3846masa/axios-cookiejar-support@*(0.1.1) (21:49:58)
../_@3846masa_axios-cookiejar-support@0.1.1@@3846masa/axios-cookiejar-support
\ No newline at end of file
../_@types_tough-cookie@2.3.1@@types/tough-cookie
\ No newline at end of file
env:
es6: true
node: true
mocha: true
extends: standard
plugins:
- standard
- promise
rules:
semi:
- error
- always
# Created by https://www.gitignore.io/api/node
### Node ###
# Logs
logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules
jspm_packages
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
The MIT License (MIT)
Copyright © 2016 3846masa
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# axios-cookiejar-support
Add [``tough-cookie``] support to [``axios``].
[``axios``]: https://github.com/mzabriskie/axios
[``tough-cookie``]: https://github.com/SalesforceEng/tough-cookie
------
[![NPM][npm-badge]][npm]
[![LICENSE][license-badge]][license]
[![CircleCI][circleci-badge]][circleci]
[![dependencies][dependencies-badge]][dependencies-david]
[![peerdependencies][peerdependencies-badge]][peerdependencies-david]
[![devdependencies][devdependencies-badge]][devdependencies-david]
[npm]: https://www.npmjs.com/package/@3846masa/axios-cookiejar-support
[license]: https://3846masa.mit-license.org
[circleci]: https://circleci.com/gh/3846masa/axios-cookiejar-support
[dependencies-david]: https://david-dm.org/3846masa/axios-cookiejar-support?view=list
[peerdependencies-david]: https://david-dm.org/3846masa/axios-cookiejar-support?type=peer&view=list
[devdependencies-david]: https://david-dm.org/3846masa/axios-cookiejar-support?type=dev&view=list
[npm-badge]: https://img.shields.io/npm/v/@3846masa/axios-cookiejar-support.svg?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAbUExURcwAAOeIiP////G7u/ri4tIZGdpFReJsbPC3t075sZwAAAAvSURBVCjPY2CgDWAThIMEsACjEhwIUCZg0dGCIqASwMAxMgXAgSzOwMAOC2TqAwBvzR4JxLaP0gAAAABJRU5ErkJggg==
[license-badge]: https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAIGNIUk0AAHomAACAhAAA%2BgAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAAVUExURSBTICJcIiNgIiZoJTuhNyt3Kf///%2BCqxSgAAAAGdFJOUwpclbn%2B4Fj6/H8AAAABYktHRAZhZrh9AAAACXBIWXMAAA3XAAAN1wFCKJt4AAAAB3RJTUUH4AkEEjEV7MDQQwAAAGBJREFUCNc1TUEKgDAMi07vE/Q%2BRD8g%2B4BbvAvi/79iMjDQJm1CC6BbDzRsZI3incIpYeYFhCaYnLiyPYnYkwWZFWoFHrSuttCmmbwXh0eJQYVON4JthZTxCzzAmyb8%2BAAKXBRyN6RyZQAAAABJRU5ErkJggg==
[circleci-badge]: https://img.shields.io/circleci/project/3846masa/axios-cookiejar-support/master.svg?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQEAYAAABPYyMiAAAAIGNIUk0AAHomAACAhAAA%2BgAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAAGYktHRP///////wlY99wAAAAHdElNRQfgCQQSJS8EYt6kAAAAiklEQVRIx2M41nqs9Xi9WDQh%2BjQQnDnz%2BS5x9KS9xJrLgN/CSXtJs5h0BzHQ1mLCDmEgL4jJpyl0AOG4JTYE4Q6gdqIi1UMM2F1OrE9xBy2xDmGgrs8wHU5nB2CGBNEOQPcBoaigThQA08AgS4QDkA3pXRChe4SBskqHiiUhreoEsmtDyhxEfKIFAG4yoGuqR9fTAAAAAElFTkSuQmCC
[dependencies-badge]: https://img.shields.io/david/3846masa/axios-cookiejar-support.svg?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAbUExURcwAAOeIiP////G7u/ri4tIZGdpFReJsbPC3t075sZwAAAAvSURBVCjPY2CgDWAThIMEsACjEhwIUCZg0dGCIqASwMAxMgXAgSzOwMAOC2TqAwBvzR4JxLaP0gAAAABJRU5ErkJggg==
[peerdependencies-badge]: https://img.shields.io/david/peer/3846masa/axios-cookiejar-support.svg?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAbUExURcwAAOeIiP////G7u/ri4tIZGdpFReJsbPC3t075sZwAAAAvSURBVCjPY2CgDWAThIMEsACjEhwIUCZg0dGCIqASwMAxMgXAgSzOwMAOC2TqAwBvzR4JxLaP0gAAAABJRU5ErkJggg==
[devdependencies-badge]: https://img.shields.io/david/dev/3846masa/axios-cookiejar-support.svg?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAbUExURcwAAOeIiP////G7u/ri4tIZGdpFReJsbPC3t075sZwAAAAvSURBVCjPY2CgDWAThIMEsACjEhwIUCZg0dGCIqASwMAxMgXAgSzOwMAOC2TqAwBvzR4JxLaP0gAAAABJRU5ErkJggg==
## Install
```sh
$ npm i axios @3846masa/axios-cookiejar-support
```
## Usage
```js
const axios = require('axios');
const axiosCookieJarSupport = require('@3846masa/axios-cookiejar-support');
const tough = require('tough-cookie');
axiosCookieJarSupport(axios);
const cookieJar = new tough.CookieJar();
axios.get('https://google.com', {
jar: cookieJar, // tough.CookieJar or boolean
withCredentials: true // If true, send cookie stored in jar
})
.then(() => {
console.log(cookieJar);
});
```
See [examples](./example).
### Extended Request Config
c.f.) https://github.com/mzabriskie/axios#request-config
```js
{
// `jar` is tough.CookieJar instance or boolean.
// If true, axios create CookieJar automatically.
jar: undefined, // default
// **IMPORTANT**
// If false, axios DONOT send cookies from cookiejar.
withCredentials: false // default
}
```
### Browser
Running on browser, this library becomes noop (``config.jar`` might be ignored).
## Contribution
1. [Fork it]
2. Create your feature branch (``git checkout -b my-new-feature``)
3. Commit your changes (``git commit -am 'Add some feature'``)
4. Push to the branch (``git push origin my-new-feature``)
5. Create new Pull Request
[Fork it]: http://github.com/3846masa/axios-cookiejar-support/fork
## LICENSE
[MIT License](https://3846masa.mit-license.org)
## Author
![3846masa icon][3846masa-icon]
[3846masa](https://github.com/3846masa)
[3846masa-icon]: https://www.gravatar.com/avatar/cfeae69aae4f4fc102960f01d35d2d86?s=50
machine:
node:
version: 4
post:
- npm install -g npm@3
timezone: Asia/Tokyo
dependencies:
override:
- npm config set progress false
- npm config set spin false
- npm install -d
test:
override:
- npm test
deployment:
production:
tag: /v\d+(\.\d+)*/
commands:
- echo -e "$NPM_USER\n$NPM_PASS\n$NPM_EMAIL" | npm login
- npm publish --access=public
'use strict';
const axios = require('axios');
const tough = require('tough-cookie');
const axiosCookieJarSupport = require('../');
axiosCookieJarSupport(axios);
const cookieJar = new tough.CookieJar();
cookieJar.setCookieSync('key=value; domain=mockbin.org', 'https://mockbin.org');
axios.get('https://mockbin.org/request', {
jar: cookieJar,
withCredentials: true // IMPORTANT!
})
.then((response) => {
const data = response.data;
console.log(data.headers.cookie);
})
.catch((err) => {
console.error(err.stack || err);
});
'use strict';
const axios = require('axios');
const tough = require('tough-cookie');
const axiosCookieJarSupport = require('../');
axiosCookieJarSupport(axios);
const cookieJar = new tough.CookieJar();
axios.defaults.jar = cookieJar;
axios.defaults.withCredentials = true;
axios.get('https://google.com')
.then((response) => {
const config = response.config;
// axios.defaults.jar === config.jar
console.log(config.jar.toJSON());
})
.catch((err) => {
console.error(err.stack || err);
});
'use strict';
const axios = require('axios');
const tough = require('tough-cookie');
const axiosCookieJarSupport = require('../');
axiosCookieJarSupport(axios);
const cookieJar = new tough.CookieJar();
axios.get('https://google.com', {
jar: cookieJar,
withCredentials: true
})
.then((response) => {
const config = response.config;
console.log(config.jar.toJSON());
})
.catch((err) => {
console.error(err.stack || err);
});
import { AxiosInstance } from 'axios';
import { CookieJar } from 'tough-cookie';
declare module 'axios' {
export interface AxiosRequestConfig {
jar?: CookieJar;
}
}
declare var axiosCookieJarSupport: (instance: AxiosInstance) => AxiosInstance;
export = axiosCookieJarSupport;
'use strict';
const tough = require('tough-cookie');
const utils = require('axios/lib/utils');
const requestInterceptorWrapper = require('./lib/request-interceptor-wrapper');
const responseInterceptorWrapper = require('./lib/response-interceptor-wrapper');
function axiosCookieJarSupport (instance) {
if (instance.create) {
const createInstance = instance.create.bind(instance);
instance.create = function create (defaultConfig) {
const newInstance = createInstance(defaultConfig);
return axiosCookieJarSupport(newInstance);
};
}
const origRequest = instance.request.bind(instance);
instance.request = function request (config) {
config._COOKIEJAR_SUPPORT_LOCAL =
config._COOKIEJAR_SUPPORT_LOCAL || {};
const local = config._COOKIEJAR_SUPPORT_LOCAL;
if (instance.defaults.jar === true) {
instance.defaults.jar = new tough.CookieJar();
}
if (!local.jar) {
if (config.jar === true) {
local.jar = (instance.defaults.jar || new tough.CookieJar());
} else if (config.jar === false) {
local.jar = false;
} else {
local.jar = (config.jar || instance.defaults.jar);
}
}
return origRequest(config);
};
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData (method) {
instance[method] = function (url, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url
}));
};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData (method) {
instance[method] = function (url, data, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url,
data: data
}));
};
});
requestInterceptorWrapper(instance);
responseInterceptorWrapper(instance);
return instance;
}
module.exports = axiosCookieJarSupport;
'use strict';
const pify = require('pify');
function requestInterceptorResolve (config) {
return Promise.resolve(config)
.then(function backupOriginalConfigs (config) {
const local = config._COOKIEJAR_SUPPORT_LOCAL;
local.backupOptions = local.backupOptions || {};
return config;
})
.then(function redirectSetup (config) {
const local = config._COOKIEJAR_SUPPORT_LOCAL;
local.redirectCount =
isFinite(config.maxRedirects) ? config.maxRedirects : 5;
local.backupOptions.maxRedirects =
local.backupOptions.maxRedirects || config.maxRedirects;
local.backupOptions.validateStatus =
local.backupOptions.validateStatus || config.validateStatus;
config.maxRedirects = 0;
config.validateStatus = undefined;
return config;
})
.then(function cookieSetup (config) {
const local = config._COOKIEJAR_SUPPORT_LOCAL;
if (local.jar && config.withCredentials) {
const getCookieString =
pify(local.jar.getCookieString.bind(local.jar));
return getCookieString(config.url)
.then(function (cookieString) {
if (!cookieString) {
return;
}
config.headers['Cookie'] =
(config.headers['Cookie'])
? cookieString + '; ' + config.headers['Cookie']
: cookieString;
}).then(function () { return config; });
}
return config;
});
};
function requestInterceptorReject (error) {
return Promise.reject(error);
};
function requestInterceptorWrapper (instance) {
instance.interceptors.request.use(
requestInterceptorResolve,
requestInterceptorReject
);
return instance;
}
module.exports = requestInterceptorWrapper;
'use strict';
const url = require('url');
const settle = require('axios/lib/core/settle');
const pify = require('pify');
function responseInterceptorResolve (response, instance) {
return Promise.resolve(response)
.then(function setCookies (response) {
const config = response.config;
const local = config._COOKIEJAR_SUPPORT_LOCAL;
if (!local.jar || !response.headers['set-cookie']) {
return response;
}
const setCookie = pify(local.jar.setCookie.bind(local.jar));
const setCookiePromiseList = [];
if (Array.isArray(response.headers['set-cookie'])) {
const cookies = response.headers['set-cookie'];
cookies.forEach(function (cookie) {
setCookiePromiseList.push(setCookie(cookie, config.url));
});
} else {
const cookie = response.headers['set-cookie'];
setCookiePromiseList.push(setCookie(cookie, config.url));
}
return Promise.all(setCookiePromiseList)
.then(function () { return response; });
})
.then(function redirectSetup (response) {
const config = response.config;
const local = config._COOKIEJAR_SUPPORT_LOCAL;
local.backupOptions.baseURL =
local.backupOptions.baseURL || config.baseURL;
local.backupOptions.url =
local.backupOptions.url || config.url;
local.backupOptions.method =
local.backupOptions.method || config.method;
config.baseURL = undefined;
config.url = config.url = url.resolve(response.config.url, response.headers['location'] || '');
local.redirectCount--;
return response;
})
.then(function redirect (response) {
const config = response.config;
const local = config._COOKIEJAR_SUPPORT_LOCAL;
if (local.redirectCount < 0 || !response.headers['location']) {
return response;
}
if (response.status !== 307) {
config.method = 'get';
}
config.maxRedirects = local.redirectCount;
return instance.request(config);
})
.then(function restoreCookieJar (response) {
const config = response.config;
const local = config._COOKIEJAR_SUPPORT_LOCAL;
if (!local || !local.jar) return response;
if (instance.defaults.jar && (!config.jar || config.jar === true)) {
instance.defaults.jar = local.jar;
}
config.jar = local.jar;
return response;
})
.then(function restoreConfigs (response) {
const config = response.config;
const local = config._COOKIEJAR_SUPPORT_LOCAL;
if (!local) return response;
for (let key in local.backupOptions) {
config[key] = local.backupOptions[key];
}
return response;
})
.then(function deleteLocals (response) {
delete response.config._COOKIEJAR_SUPPORT_LOCAL;
return response;
})
.then(function validate (response) {
return new Promise(function (resolve, reject) {
settle(resolve, reject, response);
});
});
}
function responseInterceptorReject (error) {
return Promise.reject(error);
}
function responseInterceptorWrapper (instance) {
instance.interceptors.response.use(
function (response) {
return responseInterceptorResolve(response, instance);
},
responseInterceptorReject
);
return instance;
}
module.exports = responseInterceptorWrapper;
../../../../_@types_tough-cookie@2.3.1@@types/tough-cookie
\ No newline at end of file
'use strict';
function noopEnableCookieJarSupport (instance) {
return instance;
}
module.exports = noopEnableCookieJarSupport;
{
"name": "@3846masa/axios-cookiejar-support",
"description": "Add tough-cookie support to axios.",
"version": "0.1.1",
"author": "3846masa",
"browser": {
"./index.js": "./noop.js"
},
"bugs": {
"url": "https://github.com/3846masa/axios-cookiejar-support/issues"
},
"dependencies": {
"@types/tough-cookie": "^2.3.1",
"pify": "3.0.0",
"tough-cookie": "2.3.2"
},
"devDependencies": {
"axios": "0.16.1",
"cookie": "0.3.1",
"decache": "4.1.0",
"eslint": "4.1.0",
"eslint-config-standard": "10.2.1",
"eslint-plugin-promise": "3.5.0",
"eslint-plugin-standard": "3.0.1",
"intelli-espower-loader": "1.0.1",
"mocha": "3.3.0",
"nock": "9.0.13",
"power-assert": "1.4.3"
},
"directories": {
"example": "example",
"test": "test"
},
"homepage": "https://github.com/3846masa/axios-cookiejar-support#readme",
"keywords": [
"axios",
"cookie",
"cookiejar",
"cookies",
"tough-cookie"
],
"license": "MIT",
"main": "./index.js",
"types": "./index.d.ts",
"peerDependencies": {
"axios": "^0.16.2"
},
"repository": {
"type": "git",
"url": "git+https://github.com/3846masa/axios-cookiejar-support.git"
},
"scripts": {
"postversion": "git commit --amend --allow-empty -m \"[skip ci] `git log -1 --pretty=%s`\"",
"test": "mocha --require intelli-espower-loader"
},
"_from": "@3846masa/axios-cookiejar-support@0.1.1",
"_resolved": "http://registry.npm.taobao.org/@3846masa/axios-cookiejar-support/download/@3846masa/axios-cookiejar-support-0.1.1.tgz"
}
\ No newline at end of file
'use strict';
const assert = require('power-assert');
const nock = require('nock');
const tough = require('tough-cookie');
const cookie = require('cookie');
const decache = require('decache');
const axiosCookieJarSupport = require('../');
let axios;
beforeEach(() => {
decache('axios');
axios = require('axios');
axios.defaults.validateStatus = () => true;
});
describe('axiosCookieJarSupport', () => {
it('should enable default axios instance to support cookiejar', () => {
axiosCookieJarSupport(axios);
assert.ok(axios);
});
it('should enable created axios instance to support cookiejar', () => {
const instance = axios.create();
axiosCookieJarSupport(instance);
assert.ok(instance);
});
});
describe('axios', () => {
let cookieJar;
beforeEach(() => {
axiosCookieJarSupport(axios);
cookieJar = new tough.CookieJar();
});
afterEach(() => {
nock.cleanAll();
});
it('should receive response', (done) => {
nock('http://example.com')
.get('/')
.reply(200);
axios.get('http://example.com')
.then((res) => {
assert.strictEqual(res.status, 200);
})
.then(done).catch(done);
});
context('when response has redirect', () => {
let nockHost;
beforeEach(() => {
nockHost = nock('http://example.com');
});
it('should not redirect if config.maxRedirects = 0', (done) => {
nockHost.get('/').reply(302, null, {
'Location': 'http://example.com/redirect'
});
axios.get('http://example.com', { maxRedirects: 0 })
.then((res) => {
assert.strictEqual(res.status, 302);
})
.then(done).catch(done);
});
it('should redirect 30X response', (done) => {
nockHost.post('/').reply(302, null, {
'Location': 'http://example.com/redirect'
});
nockHost.get('/redirect').reply(200);
axios.post('http://example.com')
.then((res) => {
assert.strictEqual(res.status, 200);
})
.then(done).catch(done);
});
it('should redirect many times 30X response', (done) => {
nockHost.post('/').reply(302, null, {
'Location': 'http://example.com/redirect/01'
});
nockHost.get('/redirect/01').reply(302, null, {
'Location': 'http://example.com/redirect/02'
});
nockHost.get('/redirect/02').reply(200);
axios.post('http://example.com')
.then((res) => {
assert.strictEqual(res.status, 200);
})
.then(done).catch(done);
});
it('should redirect 307 response', (done) => {
nockHost.post('/').reply(307, null, {
'Location': 'http://example.com/redirect'
});
nockHost.post('/redirect').reply(200);
axios.post('http://example.com')
.then((res) => {
assert.strictEqual(res.status, 200);
})
.then(done).catch(done);
});
it('should redirect to relative path', () => {
nockHost.post('/').reply(302, null, {
'Location': '/redirect'
});
nockHost.get('/redirect').reply(200);
return axios.post('https://example.com')
.then((res) => {
assert.strictEqual(res.status, 200);
});
});
it('should redirect to relative path, after redirect to different domain', () => {
let anotherNockHost = nock('http://another.com');
anotherNockHost.get('/redirect').reply(302, null, {
'Location': '/final'
});
anotherNockHost.get('/final').reply(200, 'final');
nockHost.post('/').reply(302, null, {
'Location': 'http://another.com/redirect'
});
return axios.post('http://example.com')
.then((res) => {
assert.strictEqual(res.status, 200);
assert.strictEqual(res.data, 'final');
});
});
it('should redirect to relative path, jumping through a different domain that is different than `baseURL`', () => {
let anotherNockHost = nock('http://another.com');
anotherNockHost.get('/redirect').reply(302, null, {
'Location': '/final'
});
anotherNockHost.get('/final').reply(200, 'final');
nockHost.post('/').reply(302, null, {
'Location': 'http://another.com/redirect'
});
return axios.create({ baseURL: 'http://example.com' })
.post('http://example.com')
.then((res) => {
assert.strictEqual(res.status, 200);
assert.strictEqual(res.data, 'final');
});
});
});
context('when hasn\'t defaults.jar', () => {
context('and hasn\'t config.jar', () => {
it('should not create cookiejar', (done) => {
nock('http://example.com')
.get('/')
.reply(200);
axios.get('http://example.com')
.then((res) => {
assert.ok(!res.config.jar);
})
.then(done).catch(done);
});
});
context('and has config.jar', () => {
it('should create cookiejar if config.jar = true', (done) => {
nock('http://example.com')
.get('/')
.reply(200);
axios.get('http://example.com', { jar: true })
.then((res) => {
assert.ok(res.config.jar);
assert.notStrictEqual(res.config.jar, true);
assert.strictEqual(res.config.jar.constructor, tough.CookieJar);
})
.then(done).catch(done);
});
it('should not create cookiejar if cookie.jar = false', (done) => {
nock('http://example.com')
.get('/')
.reply(200);
axios.get('http://example.com', { jar: false })
.then((res) => {
assert.ok(!res.config.jar);
})
.then(done).catch(done);
});
it('should use config.jar if config.jar = CookieJar', (done) => {
nock('http://example.com')
.get('/')
.reply(200);
axios.get('http://example.com', { jar: cookieJar })
.then((res) => {
assert.strictEqual(res.config.jar, cookieJar);
})
.then(done).catch(done);
});
});
});
context('when has defaults.jar', () => {
beforeEach(() => {
axios.defaults.jar = cookieJar;
});
context('and hasn\'t config.jar', () => {
it('should create cookiejar if defaults.jar = true', (done) => {
nock('http://example.com')
.get('/')
.reply(200);
axios.defaults.jar = true;
axios.get('http://example.com')
.then((res) => {
assert.ok(res.config.jar);
assert.notStrictEqual(res.config.jar, true);
assert.strictEqual(res.config.jar.constructor, tough.CookieJar);
assert.ok(axios.defaults.jar);
assert.notStrictEqual(axios.defaults.jar, true);
assert.strictEqual(axios.defaults.jar.constructor, tough.CookieJar);
})
.then(done).catch(done);
});
it('should use defaults.jar if defaults.jar = CookieJar', (done) => {
nock('http://example.com')
.get('/')
.reply(200);
axios.get('http://example.com')
.then((res) => {
assert.strictEqual(res.config.jar, cookieJar);
assert.strictEqual(res.config.jar, axios.defaults.jar);
})
.then(done).catch(done);
});
});
context('and has config.jar', () => {
it('should create cookiejar if defaults.jar = true && config.jar = true', (done) => {
nock('http://example.com')
.get('/')
.reply(200);
axios.defaults.jar = true;
axios.get('http://example.com', { jar: true })
.then((res) => {
assert.ok(res.config.jar);
assert.notStrictEqual(res.config.jar, true);
assert.strictEqual(res.config.jar.constructor, tough.CookieJar);
assert.ok(axios.defaults.jar);
assert.notStrictEqual(axios.defaults.jar, true);
assert.strictEqual(axios.defaults.jar.constructor, tough.CookieJar);
})
.then(done).catch(done);
});
it('should use defaults.jar if config.jar = true', (done) => {
nock('http://example.com')
.get('/')
.reply(200);
axios.get('http://example.com', { jar: true })
.then((res) => {
assert.strictEqual(res.config.jar, axios.defaults.jar);
})
.then(done).catch(done);
});
it('should not create cookiejar if config.jar = false', (done) => {
nock('http://example.com')
.get('/')
.reply(200);
axios.get('http://example.com', { jar: false })
.then((res) => {
assert.ok(!res.config.jar);
})
.then(done).catch(done);
});
it('should use config.jar if config.jar = CookieJar', (done) => {
const anotherCookieJar = new tough.CookieJar();
nock('http://example.com')
.get('/')
.reply(200);
axios.get('http://example.com', { jar: anotherCookieJar })
.then((res) => {
assert.notStrictEqual(res.config.jar, axios.defaults.jar);
})
.then(done).catch(done);
});
});
});
context('when has cookiejar', () => {
let originalCookie;
beforeEach(() => {
axios.defaults.jar = cookieJar;
originalCookie = new tough.Cookie({
key: 'test',
value: 'value'
});
});
it('should store cookie', (done) => {
nock('http://example.com')
.get('/')
.reply(200, null, {
'Set-Cookie': originalCookie.toString()
});
axios.get('http://example.com')
.then((res) => {
const receivedCookies = res.config.jar.getCookiesSync('http://example.com');
assert.strictEqual(receivedCookies.length, 1);
assert.strictEqual(receivedCookies[0].key, originalCookie.key);
assert.strictEqual(receivedCookies[0].value, originalCookie.value);
})
.then(done).catch(done);
});
it('should send cookie if withCredentials = true', (done) => {
cookieJar.setCookieSync(originalCookie, 'http://example.com');
nock('http://example.com')
.matchHeader('cookie', (value) => {
assert.ok(value);
const receivedCookie = cookie.parse(value);
assert.ok(originalCookie.key in receivedCookie);
assert.strictEqual(receivedCookie[originalCookie.key], originalCookie.value);
return true;
})
.get('/')
.reply(200);
axios.get('http://example.com', { withCredentials: true })
.then((res) => {
assert.strictEqual(res.status, 200);
}).then(done).catch(done);
});
it('should not send cookie if withCredentials = false', (done) => {
cookieJar.setCookieSync(originalCookie, 'http://example.com');
nock('http://example.com')
.matchHeader('cookie', (value) => {
assert.ok(!value);
return true;
})
.get('/')
.reply(200);
axios.get('http://example.com', { withCredentials: false })
.then((res) => {
assert.strictEqual(res.status, 200);
}).then(done).catch(done);
});
it('should send all cookies if set headers[\'Cookie\']', (done) => {
cookieJar.setCookieSync(originalCookie, 'http://example.com');
nock('http://example.com')
.matchHeader('cookie', (value) => {
assert.ok(value);
const receivedCookie = cookie.parse(value);
assert.ok(originalCookie.key in receivedCookie);
assert.strictEqual(receivedCookie[originalCookie.key], originalCookie.value);
assert.ok('from' in receivedCookie);
assert.strictEqual(receivedCookie['from'], 'string');
return true;
})
.get('/')
.reply(200);
axios.get('http://example.com', {
headers: { 'Cookie': 'from=string' },
withCredentials: true
})
.then((res) => {
assert.strictEqual(res.status, 200);
}).then(done).catch(done);
});
});
});
Mon Aug 07 2017 19:51:45 GMT+0800 (CST)
\ No newline at end of file
MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
# Installation
> `npm install --save @types/tough-cookie`
# Summary
This package contains type definitions for tough-cookie (https://github.com/salesforce/tough-cookie).
# Details
Files were exported from https://www.github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/tough-cookie
Additional Details
* Last updated: Fri, 14 Jul 2017 14:18:49 GMT
* Dependencies: none
* Global values: none
# Credits
These definitions were written by Leonard Thieu <https://github.com/leonard-thieu>.
// Type definitions for tough-cookie 2.3
// Project: https://github.com/salesforce/tough-cookie
// Definitions by: Leonard Thieu <https://github.com/leonard-thieu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/**
* Parse a cookie date string into a Date.
* Parses according to RFC6265 Section 5.1.1, not Date.parse().
*/
export function parseDate(string: string): Date;
/**
* Format a Date into a RFC1123 string (the RFC6265-recommended format).
*/
export function formatDate(date: Date): string;
/**
* Transforms a domain-name into a canonical domain-name.
* The canonical domain-name is a trimmed, lowercased, stripped-of-leading-dot
* and optionally punycode-encoded domain-name (Section 5.1.2 of RFC6265).
* For the most part, this function is idempotent (can be run again on its output without ill effects).
*/
export function canonicalDomain(str: string): string;
/**
* Answers "does this real domain match the domain in a cookie?".
* The str is the "current" domain-name and the domStr is the "cookie" domain-name.
* Matches according to RFC6265 Section 5.1.3, but it helps to think of it as a "suffix match".
*
* The canonicalize parameter will run the other two paramters through canonicalDomain or not.
*/
export function domainMatch(str: string, domStr: string, canonicalize?: boolean): boolean;
/**
* Given a current request/response path, gives the Path apropriate for storing in a cookie.
* This is basically the "directory" of a "file" in the path, but is specified by Section 5.1.4 of the RFC.
*
* The path parameter MUST be only the pathname part of a URI (i.e. excludes the hostname, query, fragment, etc.).
* This is the .pathname property of node's uri.parse() output.
*/
export function defaultPath(path: string): string;
/**
* Answers "does the request-path path-match a given cookie-path?" as per RFC6265 Section 5.1.4.
* Returns a boolean.
*
* This is essentially a prefix-match where cookiePath is a prefix of reqPath.
*/
export function pathMatch(reqPath: string, cookiePath: string): boolean;
/**
* alias for Cookie.fromJSON(string)
*/
export function fromJSON(string: string): Cookie;
export function getPublicSuffix(hostname: string): string | null;
export function cookieCompare(a: Cookie, b: Cookie): number;
export function permuteDomain(domain: string): string[];
export function permutePath(path: string): string[];
// region Cookie
export class Cookie {
static parse(cookieString: string, options?: Cookie.ParseOptions): Cookie | undefined;
static fromJSON(strOrObj: string | object): Cookie | null;
constructor(properties?: Cookie.Properties);
// TODO: Some of the following properties might actually be nullable.
key: string;
value: string;
expires: Date;
maxAge: number | 'Infinity' | '-Infinity';
domain: string;
path: string;
secure: boolean;
httpOnly: boolean;
extensions: string[];
creation: Date;
creationIndex: number;
hostOnly: boolean | null;
pathIsDefault: boolean | null;
lastAccessed: Date | null;
toString(): string;
cookieString(): string;
setExpires(String: string): void;
setMaxAge(number: number): void;
expiryTime(now?: number): number | typeof Infinity;
expiryDate(now?: number): Date;
TTL(now?: Date): number | typeof Infinity;
canonicalizedDomain(): string;
cdomain(): string;
toJSON(): { [key: string]: any; };
clone(): Cookie;
validate(): boolean | string;
}
export namespace Cookie {
interface ParseOptions {
loose?: boolean;
}
interface Properties {
key?: string;
value?: string;
expires?: Date;
maxAge?: number | 'Infinity' | '-Infinity';
domain?: string;
path?: string;
secure?: boolean;
httpOnly?: boolean;
extensions?: string[];
creation?: Date;
creationIndex?: number;
hostOnly?: boolean;
pathIsDefault?: boolean;
lastAccessed?: Date;
}
interface Serialized {
[key: string]: any;
}
}
// endregion
// region CookieJar
export class CookieJar {
static deserialize(serialized: CookieJar.Serialized | string, store: Store, cb: (err: Error | null, object: CookieJar) => void): void;
static deserialize(serialized: CookieJar.Serialized | string, cb: (err: Error | null, object: CookieJar) => void): void;
static deserializeSync(serialized: CookieJar.Serialized | string): CookieJar;
static fromJSON(string: string): CookieJar;
constructor(store?: Store, options?: CookieJar.Options);
setCookie(cookieOrString: Cookie | string, currentUrl: string, options: CookieJar.SetCookieOptions, cb: (err: Error | null, cookie: Cookie) => void): void;
setCookie(cookieOrString: Cookie | string, currentUrl: string, cb: (err: Error, cookie: Cookie) => void): void;
setCookieSync(cookieOrString: Cookie | string, currentUrl: string, options: CookieJar.SetCookieOptions): void;
getCookies(currentUrl: string, options: CookieJar.GetCookiesOptions, cb: (err: Error | null, cookies: Cookie[]) => void): void;
getCookies(currentUrl: string, cb: (err: Error | null, cookies: Cookie[]) => void): void;
getCookiesSync(currentUrl: string, options?: CookieJar.GetCookiesOptions): Cookie[];
getCookieString(currentUrl: string, options: CookieJar.GetCookiesOptions, cb: (err: Error | null, cookies: string) => void): void;
getCookieString(currentUrl: string, cb: (err: Error | null, cookies: string) => void): void;
getCookieStringSync(currentUrl: string, options?: CookieJar.GetCookiesOptions): string;
getSetCookieStrings(currentUrl: string, options: CookieJar.GetCookiesOptions, cb: (err: Error | null, cookies: string) => void): void;
getSetCookieStrings(currentUrl: string, cb: (err: Error | null, cookies: string) => void): void;
getSetCookieStringsSync(currentUrl: string, options?: CookieJar.GetCookiesOptions): string;
serialize(cb: (err: Error | null, serializedObject: CookieJar.Serialized) => void): void;
serializeSync(): CookieJar.Serialized;
toJSON(): CookieJar.Serialized;
clone(store: Store, cb: (err: Error | null, newJar: CookieJar) => void): void;
clone(cb: (err: Error | null, newJar: CookieJar) => void): void;
cloneSync(store: Store): CookieJar;
}
export namespace CookieJar {
interface Options {
rejectPublicSuffixes?: boolean;
looseMode?: boolean;
}
interface SetCookieOptions {
http?: boolean;
secure?: boolean;
now?: Date;
ignoreError?: boolean;
}
interface GetCookiesOptions {
http?: boolean;
secure?: boolean;
date?: Date;
expire?: boolean;
allPoints?: boolean;
}
interface Serialized {
version: string;
storeType: string;
rejectPublicSuffixes: boolean;
cookies: Cookie.Serialized[];
}
}
// endregion
// region Store
export abstract class Store {
findCookie(domain: string, path: string, key: string, cb: (err: Error | null, cookie: Cookie | null) => void): void;
findCookies(domain: string, path: string, cb: (err: Error | null, cookie: Cookie[]) => void): void;
putCookie(cookie: Cookie, cb: (err: Error | null) => void): void;
updateCookie(oldCookie: Cookie, newCookie: Cookie, cb: (err: Error | null) => void): void;
removeCookie(domain: string, path: string, key: string, cb: (err: Error | null) => void): void;
removeCookies(domain: string, path: string, cb: (err: Error | null) => void): void;
getAllCookies(cb: (err: Error | null, cookie: Cookie[]) => void): void;
}
export class MemoryCookieStore extends Store { }
// endregion
{
"name": "@types/tough-cookie",
"version": "2.3.1",
"description": "TypeScript definitions for tough-cookie",
"license": "MIT",
"contributors": [
{
"name": "Leonard Thieu",
"url": "https://github.com/leonard-thieu"
}
],
"main": "",
"repository": {
"type": "git",
"url": "https://www.github.com/DefinitelyTyped/DefinitelyTyped.git"
},
"scripts": {},
"dependencies": {},
"peerDependencies": {},
"typesPublisherContentHash": "2a7d2b6b4c215d564939a5afc228cec98bc527bb3743f878b8e5fd6758e332bc",
"typeScriptVersion": "2.2",
"_from": "@types/tough-cookie@2.3.1",
"_resolved": "http://registry.npm.taobao.org/@types/tough-cookie/download/@types/tough-cookie-2.3.1.tgz"
}
\ No newline at end of file
File mode changed from 100644 to 100755
Mon Aug 07 2017 19:51:45 GMT+0800 (CST)
\ No newline at end of file
'use strict';
const processFn = (fn, opts) => function () {
const P = opts.promiseModule;
const args = new Array(arguments.length);
for (let i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
return new P((resolve, reject) => {
if (opts.errorFirst) {
args.push(function (err, result) {
if (opts.multiArgs) {
const results = new Array(arguments.length - 1);
for (let i = 1; i < arguments.length; i++) {
results[i - 1] = arguments[i];
}
if (err) {
results.unshift(err);
reject(results);
} else {
resolve(results);
}
} else if (err) {
reject(err);
} else {
resolve(result);
}
});
} else {
args.push(function (result) {
if (opts.multiArgs) {
const results = new Array(arguments.length - 1);
for (let i = 0; i < arguments.length; i++) {
results[i] = arguments[i];
}
resolve(results);
} else {
resolve(result);
}
});
}
fn.apply(this, args);
});
};
module.exports = (obj, opts) => {
opts = Object.assign({
exclude: [/.+(Sync|Stream)$/],
errorFirst: true,
promiseModule: Promise
}, opts);
const filter = key => {
const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key);
return opts.include ? opts.include.some(match) : !opts.exclude.some(match);
};
let ret;
if (typeof obj === 'function') {
ret = function () {
if (opts.excludeMain) {
return obj.apply(this, arguments);
}
return processFn(obj, opts).apply(this, arguments);
};
} else {
ret = Object.create(Object.getPrototypeOf(obj));
}
for (const key in obj) { // eslint-disable-line guard-for-in
const x = obj[key];
ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x;
}
return ret;
};
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
"name": "pify",
"version": "3.0.0",
"description": "Promisify a callback-style function",
"license": "MIT",
"repository": "sindresorhus/pify",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=4"
},
"scripts": {
"test": "xo && ava && npm run optimization-test",
"optimization-test": "node --allow-natives-syntax optimization-test.js"
},
"files": [
"index.js"
],
"keywords": [
"promise",
"promises",
"promisify",
"all",
"denodify",
"denodeify",
"callback",
"cb",
"node",
"then",
"thenify",
"convert",
"transform",
"wrap",
"wrapper",
"bind",
"to",
"async",
"await",
"es2015",
"bluebird"
],
"devDependencies": {
"ava": "*",
"pinkie-promise": "^2.0.0",
"v8-natives": "^1.0.0",
"xo": "*"
},
"_from": "pify@3.0.0",
"_resolved": "http://registry.npm.taobao.org/pify/download/pify-3.0.0.tgz"
}
\ No newline at end of file
# pify [![Build Status](https://travis-ci.org/sindresorhus/pify.svg?branch=master)](https://travis-ci.org/sindresorhus/pify)
> Promisify a callback-style function
## Install
```
$ npm install --save pify
```
## Usage
```js
const fs = require('fs');
const pify = require('pify');
// Promisify a single function
pify(fs.readFile)('package.json', 'utf8').then(data => {
console.log(JSON.parse(data).name);
//=> 'pify'
});
// Promisify all methods in a module
pify(fs).readFile('package.json', 'utf8').then(data => {
console.log(JSON.parse(data).name);
//=> 'pify'
});
```
## API
### pify(input, [options])
Returns a `Promise` wrapped version of the supplied function or module.
#### input
Type: `Function` `Object`
Callback-style function or module whose methods you want to promisify.
#### options
##### multiArgs
Type: `boolean`<br>
Default: `false`
By default, the promisified function will only return the second argument from the callback, which works fine for most APIs. This option can be useful for modules like `request` that return multiple arguments. Turning this on will make it return an array of all arguments from the callback, excluding the error argument, instead of just the second argument. This also applies to rejections, where it returns an array of all the callback arguments, including the error.
```js
const request = require('request');
const pify = require('pify');
pify(request, {multiArgs: true})('https://sindresorhus.com').then(result => {
const [httpResponse, body] = result;
});
```
##### include
Type: `string[]` `RegExp[]`
Methods in a module to promisify. Remaining methods will be left untouched.
##### exclude
Type: `string[]` `RegExp[]`<br>
Default: `[/.+(Sync|Stream)$/]`
Methods in a module **not** to promisify. Methods with names ending with `'Sync'` are excluded by default.
##### excludeMain
Type: `boolean`<br>
Default: `false`
If given module is a function itself, it will be promisified. Turn this option on if you want to promisify only methods of the module.
```js
const pify = require('pify');
function fn() {
return true;
}
fn.method = (data, callback) => {
setImmediate(() => {
callback(null, data);
});
};
// Promisify methods but not `fn()`
const promiseFn = pify(fn, {excludeMain: true});
if (promiseFn()) {
promiseFn.method('hi').then(data => {
console.log(data);
});
}
```
##### errorFirst
Type: `boolean`<br>
Default: `true`
Whether the callback has an error as the first argument. You'll want to set this to `false` if you're dealing with an API that doesn't have an error as the first argument, like `fs.exists()`, some browser APIs, Chrome Extension APIs, etc.
##### promiseModule
Type: `Function`
Custom promise module to use instead of the native one.
Check out [`pinkie-promise`](https://github.com/floatdrop/pinkie-promise) if you need a tiny promise polyfill.
## Related
- [p-event](https://github.com/sindresorhus/p-event) - Promisify an event by waiting for it to be emitted
- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently
- [More…](https://github.com/sindresorhus/promise-fun)
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
/.idea/
/coverage/
/test/
/.editorconfig
/.eslintrc.json
/.gitignore
/.publishrc
/.travis.yml
/gulpfile.js
.DS_Store
npm-debug.log
\ No newline at end of file
Mon Aug 07 2017 15:31:49 GMT+0800 (CST)
\ No newline at end of file
ISC License
Copyright (c) 2016, Nicolai Kamenzky and contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
\ No newline at end of file
<a href="http://promisesaplus.com/">
<img src="https://promises-aplus.github.io/promises-spec/assets/logo-small.png" align="right" alt="Promises/A+ logo" />
</a>
# request-promise-core
[![Gitter](https://img.shields.io/badge/gitter-join_chat-blue.svg?style=flat-square&maxAge=2592000)](https://gitter.im/request/request-promise?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Build Status](https://img.shields.io/travis/request/promise-core/master.svg?style=flat-square&maxAge=2592000)](https://travis-ci.org/request/promise-core)
[![Coverage Status](https://img.shields.io/coveralls/request/promise-core.svg?style=flat-square&maxAge=2592000)](https://coveralls.io/r/request/promise-core)
[![Dependency Status](https://img.shields.io/david/request/promise-core.svg?style=flat-square&maxAge=2592000)](https://david-dm.org/request/promise-core)
[![Known Vulnerabilities](https://snyk.io/test/npm/promise-core/badge.svg?style=flat-square&maxAge=2592000)](https://snyk.io/test/npm/promise-core)
This package is the core for the following packages:
- [`request-promise`](https://github.com/request/request-promise)
- [`request-promise-any`](https://github.com/request/request-promise-any)
- [`request-promise-bluebird`](https://github.com/request/request-promise-bluebird)
- [`request-promise-native`](https://github.com/request/request-promise-native)
`request-promise-core` contains the core logic to add Promise support to [`request`](https://github.com/request/request).
Please use one of the libraries above. It is only recommended to use this library directly, if you have very specific requirements.
## Installation for `request@^2.34`
This module is installed via npm:
```
npm install --save request
npm install --save request-promise-core
```
`request` is defined as a peer-dependency and thus has to be installed separately.
## Usage for `request@^2.34`
``` js
// 1. Load the request library
// Only use a direct require if you are 100% sure that:
// - Your project does not use request directly. That is without the Promise capabilities by calling require('request').
// - Any of the installed libraries use request.
// ...because Request's prototype will be patched in step 2.
/* var request = require('request'); */
// Instead use:
var stealthyRequire = require('stealthy-require');
var request = stealthyRequire(require.cache, function () {
return require('request');
});
// 2. Add Promise support to request
var configure = require('request-promise-core/configure/request2');
configure({
request: request,
// Pass your favorite ES6-compatible promise implementation
PromiseImpl: Promise,
// Expose all methods of the promise instance you want to call on the request(...) call
expose: [
'then', // Allows to use request(...).then(...)
'catch', // Allows to use request(...).catch(...)
'promise' // Allows to use request(...).promise() which returns the promise instance
],
// Optional: Pass a callback that is called within the Promise constructor
constructorMixin: function (resolve, reject) {
// `this` is the request object
// Additional arguments may be passed depending on the PromiseImpl used
}
});
// 3. Use request with its promise capabilities
// E.g. crawl a web page:
request('http://www.google.com')
.then(function (htmlString) {
// Process html...
})
.catch(function (err) {
// Crawling failed...
});
```
## Installation and Usage for `request@next`
[Request Next](https://github.com/request/request/issues/1982) is still in alpha. However, `request-promise-core` is already designed to be compatible and ships with a configuration helper – `require('request-promise-core/configure/request-next')` – that is [used by `request-promise`](https://github.com/request/request-promise/blob/next/lib/rp.js) in its "next" branch.
## Contributing
To set up your development environment:
1. clone the repo to your desktop,
2. in the shell `cd` to the main folder,
3. hit `npm install`,
4. hit `npm install gulp -g` if you haven't installed gulp globally yet, and
5. run `gulp dev`. (Or run `node ./node_modules/.bin/gulp dev` if you don't want to install gulp globally.)
`gulp dev` watches all source files and if you save some changes it will lint the code and execute all tests. The test coverage report can be viewed from `./coverage/lcov-report/index.html`.
If you want to debug a test you should use `gulp test-without-coverage` to run all tests without obscuring the code by the test coverage instrumentation.
## Change History
- 1.1.1 (2016-08-08)
- Renamed package to `request-promise-core` because there where [too many issues](https://github.com/request/request-promise/issues/137) with the scoped package name `@request/promise-core`
- 1.1.0 (2016-07-30)
- Added `constructorMixin` option to enable [request/request-promise#123](https://github.com/request/request-promise/pull/123)
- 1.0.0 (2016-07-15)
- All tests green, ready for prime time
- 1.0.0-rc.1 (2016-07-10)
- Reimplementation of core logic based on `request-promise@3.0.0`
- Plus `transform2xxOnly` option (fixes [request/request-promise#131](https://github.com/request/request-promise/issues/131))
## License (ISC)
In case you never heard about the [ISC license](http://en.wikipedia.org/wiki/ISC_license) it is functionally equivalent to the MIT license.
See the [LICENSE file](LICENSE) for details.
\ No newline at end of file
'use strict';
var core = require('../'),
isArray = require('lodash/isArray'),
isFunction = require('lodash/isFunction'),
isObjectLike = require('lodash/isObjectLike');
module.exports = function (options) {
var errorText = 'Please verify options'; // For better minification because this string is repeating
if (!isObjectLike(options)) {
throw new TypeError(errorText);
}
if (!isFunction(options.client)) {
throw new TypeError(errorText + '.client');
}
if (!isArray(options.expose) || options.expose.length === 0) {
throw new TypeError(errorText + '.expose');
}
var thenExposed = false;
for ( var i = 0; i < options.expose.length; i+=1 ) {
if (options.expose[i] === 'then') {
thenExposed = true;
break;
}
}
if (!thenExposed) {
throw new Error('Please expose "then"');
}
var plumbing = core({
PromiseImpl: options.PromiseImpl,
constructorMixin: options.constructorMixin
});
return function (requestOptions) {
var self = {};
plumbing.init.call(self, requestOptions);
var request = options.client(requestOptions);
for ( var k = 0; k < options.expose.length; k+=1 ) {
var method = options.expose[k];
plumbing[ method === 'promise' ? 'exposePromise' : 'exposePromiseMethod' ](
request,
self,
'_rp_promise',
method
);
}
return request;
};
};
'use strict';
var core = require('../'),
isArray = require('lodash/isArray'),
isFunction = require('lodash/isFunction'),
isObjectLike = require('lodash/isObjectLike');
module.exports = function (options) {
var errorText = 'Please verify options'; // For better minification because this string is repeating
if (!isObjectLike(options)) {
throw new TypeError(errorText);
}
if (!isFunction(options.request)) {
throw new TypeError(errorText + '.request');
}
if (!isArray(options.expose) || options.expose.length === 0) {
throw new TypeError(errorText + '.expose');
}
var plumbing = core({
PromiseImpl: options.PromiseImpl,
constructorMixin: options.constructorMixin
});
// Intercepting Request's init method
var originalInit = options.request.Request.prototype.init;
options.request.Request.prototype.init = function RP$initInterceptor(requestOptions) {
// Init may be called again - currently in case of redirects
if (isObjectLike(requestOptions) && !this._callback && !this._rp_promise) {
plumbing.init.call(this, requestOptions);
}
return originalInit.apply(this, arguments);
};
// Exposing the Promise capabilities
var thenExposed = false;
for ( var i = 0; i < options.expose.length; i+=1 ) {
var method = options.expose[i];
plumbing[ method === 'promise' ? 'exposePromise' : 'exposePromiseMethod' ](
options.request.Request.prototype,
null,
'_rp_promise',
method
);
if (method === 'then') {
thenExposed = true;
}
}
if (!thenExposed) {
throw new Error('Please expose "then"');
}
};
'use strict';
module.exports = require('./lib/errors.js');
'use strict';
function RequestError(cause, options, response) {
this.name = 'RequestError';
this.message = String(cause);
this.cause = cause;
this.error = cause; // legacy attribute
this.options = options;
this.response = response;
if (Error.captureStackTrace) { // required for non-V8 environments
Error.captureStackTrace(this);
}
}
RequestError.prototype = Object.create(Error.prototype);
RequestError.prototype.constructor = RequestError;
function StatusCodeError(statusCode, body, options, response) {
this.name = 'StatusCodeError';
this.statusCode = statusCode;
this.message = statusCode + ' - ' + (JSON && JSON.stringify ? JSON.stringify(body) : body);
this.error = body; // legacy attribute
this.options = options;
this.response = response;
if (Error.captureStackTrace) { // required for non-V8 environments
Error.captureStackTrace(this);
}
}
StatusCodeError.prototype = Object.create(Error.prototype);
StatusCodeError.prototype.constructor = StatusCodeError;
function TransformError(cause, options, response) {
this.name = 'TransformError';
this.message = String(cause);
this.cause = cause;
this.error = cause; // legacy attribute
this.options = options;
this.response = response;
if (Error.captureStackTrace) { // required for non-V8 environments
Error.captureStackTrace(this);
}
}
TransformError.prototype = Object.create(Error.prototype);
TransformError.prototype.constructor = TransformError;
module.exports = {
RequestError: RequestError,
StatusCodeError: StatusCodeError,
TransformError: TransformError
};
'use strict';
var errors = require('./errors.js'),
isFunction = require('lodash/isFunction'),
isObjectLike = require('lodash/isObjectLike'),
isString = require('lodash/isString'),
isUndefined = require('lodash/isUndefined');
module.exports = function (options) {
var errorText = 'Please verify options'; // For better minification because this string is repeating
if (!isObjectLike(options)) {
throw new TypeError(errorText);
}
if (!isFunction(options.PromiseImpl)) {
throw new TypeError(errorText + '.PromiseImpl');
}
if (!isUndefined(options.constructorMixin) && !isFunction(options.constructorMixin)) {
throw new TypeError(errorText + '.PromiseImpl');
}
var PromiseImpl = options.PromiseImpl;
var constructorMixin = options.constructorMixin;
var plumbing = {};
plumbing.init = function (requestOptions) {
var self = this;
self._rp_promise = new PromiseImpl(function (resolve, reject) {
self._rp_resolve = resolve;
self._rp_reject = reject;
if (constructorMixin) {
constructorMixin.apply(self, arguments); // Using arguments since specific Promise libraries may pass additional parameters
}
});
self._rp_callbackOrig = requestOptions.callback;
requestOptions.callback = self.callback = function RP$callback(err, response, body) {
plumbing.callback.call(self, err, response, body);
};
if (isString(requestOptions.method)) {
requestOptions.method = requestOptions.method.toUpperCase();
}
requestOptions.transform = requestOptions.transform || plumbing.defaultTransformations[requestOptions.method];
self._rp_options = requestOptions;
self._rp_options.simple = requestOptions.simple !== false;
self._rp_options.resolveWithFullResponse = requestOptions.resolveWithFullResponse === true;
self._rp_options.transform2xxOnly = requestOptions.transform2xxOnly === true;
};
plumbing.defaultTransformations = {
HEAD: function (body, response, resolveWithFullResponse) {
return resolveWithFullResponse ? response : response.headers;
}
};
plumbing.callback = function (err, response, body) {
var self = this;
var origCallbackThrewException = false, thrownException = null;
if (isFunction(self._rp_callbackOrig)) {
try {
self._rp_callbackOrig.apply(self, arguments); // TODO: Apply to self mimics behavior of request@2. Is that also right for request@next?
} catch (e) {
origCallbackThrewException = true;
thrownException = e;
}
}
var is2xx = !err && /^2/.test('' + response.statusCode);
if (err) {
self._rp_reject(new errors.RequestError(err, self._rp_options, response));
} else if (self._rp_options.simple && !is2xx) {
if (isFunction(self._rp_options.transform) && self._rp_options.transform2xxOnly === false) {
(new PromiseImpl(function (resolve) {
resolve(self._rp_options.transform(body, response, self._rp_options.resolveWithFullResponse)); // transform may return a Promise
}))
.then(function (transformedResponse) {
self._rp_reject(new errors.StatusCodeError(response.statusCode, body, self._rp_options, transformedResponse));
})
.catch(function (transformErr) {
self._rp_reject(new errors.TransformError(transformErr, self._rp_options, response));
});
} else {
self._rp_reject(new errors.StatusCodeError(response.statusCode, body, self._rp_options, response));
}
} else {
if (isFunction(self._rp_options.transform) && (is2xx || self._rp_options.transform2xxOnly === false)) {
(new PromiseImpl(function (resolve) {
resolve(self._rp_options.transform(body, response, self._rp_options.resolveWithFullResponse)); // transform may return a Promise
}))
.then(function (transformedResponse) {
self._rp_resolve(transformedResponse);
})
.catch(function (transformErr) {
self._rp_reject(new errors.TransformError(transformErr, self._rp_options, response));
});
} else if (self._rp_options.resolveWithFullResponse) {
self._rp_resolve(response);
} else {
self._rp_resolve(body);
}
}
if (origCallbackThrewException) {
throw thrownException;
}
};
plumbing.exposePromiseMethod = function (exposeTo, bindTo, promisePropertyKey, methodToExpose, exposeAs) {
exposeAs = exposeAs || methodToExpose;
if (exposeAs in exposeTo) {
throw new Error('Unable to expose method "' + exposeAs + '"');
}
exposeTo[exposeAs] = function RP$exposed() {
var self = bindTo || this;
return self[promisePropertyKey][methodToExpose].apply(self[promisePropertyKey], arguments);
};
};
plumbing.exposePromise = function (exposeTo, bindTo, promisePropertyKey, exposeAs) {
exposeAs = exposeAs || 'promise';
if (exposeAs in exposeTo) {
throw new Error('Unable to expose method "' + exposeAs + '"');
}
exposeTo[exposeAs] = function RP$promise() {
var self = bindTo || this;
return self[promisePropertyKey];
};
};
return plumbing;
};
{
"name": "request-promise-core",
"version": "1.1.1",
"description": "Core Promise support implementation for the simplified HTTP request client 'request'.",
"keywords": [
"xhr",
"http",
"https",
"promise",
"request",
"then",
"thenable",
"core"
],
"main": "./lib/plumbing.js",
"scripts": {
"test": "./node_modules/.bin/gulp ci",
"test-publish": "./node_modules/.bin/gulp ci-no-cov",
"publish-please": "publish-please",
"prepublish": "publish-please guard"
},
"repository": {
"type": "git",
"url": "git+https://github.com/request/promise-core.git"
},
"author": "Nicolai Kamenzky (https://github.com/analog-nico)",
"license": "ISC",
"bugs": {
"url": "https://github.com/request/promise-core/issues"
},
"homepage": "https://github.com/request/promise-core#readme",
"engines": {
"node": ">=0.10.0"
},
"dependencies": {
"lodash": "^4.13.1"
},
"peerDependencies": {
"request": "^2.34"
},
"devDependencies": {
"@request/api": "^0.6.0",
"@request/client": "^0.1.0",
"bluebird": "~3.4.1",
"body-parser": "~1.15.2",
"chai": "~3.5.0",
"chalk": "~1.1.3",
"gulp": "~3.9.1",
"gulp-coveralls": "~0.1.4",
"gulp-eslint": "~2.1.0",
"gulp-istanbul": "~1.0.0",
"gulp-mocha": "~2.2.0",
"node-version": "~1.0.0",
"publish-please": "~2.1.4",
"request": "^2.34.0",
"rimraf": "~2.5.3",
"run-sequence": "~1.2.2",
"stealthy-require": "~1.0.0"
},
"_from": "request-promise-core@1.1.1",
"_resolved": "http://registry.npm.taobao.org/request-promise-core/download/request-promise-core-1.1.1.tgz"
}
\ No newline at end of file
/.idea/
/coverage/
/test/
/.editorconfig
/.eslintrc.json
/.gitignore
/.publishrc
/.travis.yml
/gulpfile.js
/run-request-tests.md
.DS_Store
npm-debug.log
\ No newline at end of file
Mon Aug 07 2017 15:31:47 GMT+0800 (CST)
\ No newline at end of file
ISC License
Copyright (c) 2017, Nicolai Kamenzky, Ty Abonil, and contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
\ No newline at end of file
<a href="http://promisesaplus.com/">
<img src="https://promises-aplus.github.io/promises-spec/assets/logo-small.png" align="right" alt="Promises/A+ logo" />
</a>
# Request-Promise
[![Gitter](https://img.shields.io/badge/gitter-join_chat-blue.svg?style=flat-square&maxAge=2592000)](https://gitter.im/request/request-promise?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Build Status](https://img.shields.io/travis/request/request-promise/master.svg?style=flat-square&maxAge=2592000)](https://travis-ci.org/request/request-promise)
[![Coverage Status](https://img.shields.io/coveralls/request/request-promise.svg?style=flat-square&maxAge=2592000)](https://coveralls.io/r/request/request-promise)
[![Dependency Status](https://img.shields.io/david/request/request-promise.svg?style=flat-square&maxAge=2592000)](https://david-dm.org/request/request-promise)
[![Known Vulnerabilities](https://snyk.io/test/npm/request-promise/badge.svg?style=flat-square&maxAge=2592000)](https://snyk.io/test/npm/request-promise)
The simplified HTTP request client 'request' with Promise support. Powered by Bluebird.
[Request](https://github.com/request/request) and [Bluebird](https://github.com/petkaantonov/bluebird) are pretty awesome, but I found myself using the same design pattern. Request-Promise adds a Bluebird-powered `.then(...)` method to Request call objects. By default, http response codes other than 2xx will cause the promise to be rejected. This can be overwritten by setting `options.simple = false`.
Also check out the new libraries that are **very similar to `request-promise` v4**:
- [`request-promise-native`](https://github.com/request/request-promise-native) v1 &ndash; Does not depend on Bluebird and uses native ES6 promises instead.
- [`request-promise-any`](https://github.com/request/request-promise-any) v1 &ndash; Allows you to register any Promise library supported by [`any-promise`](https://www.npmjs.com/package/any-promise).
---
## Migration from v3 to v4
1. `request` became a peer dependency. Thus make sure that `request` is installed into your project as a direct dependency. (`npm install --save request`)
2. Continuation Local Storage is no longer supported. However, you [can get back the support](https://github.com/request/request-promise/wiki/Getting-Back-Support-for-Continuation-Local-Storage) by using `request-promise-any`.
3. When you migrated your `transform` function to v3 and had to add `if (!(/^2/.test('' + response.statusCode))) { return resolveWithFullResponse ? response : body; }` you may now set the option `transform2xxOnly = true` instead.
## Migration from v2 to v3
1. The handling of the `transform` function got overhauled. This has two effects:
- `StatusCodeError.response` is the transformed instead of the original response now. This error is thrown for non-2xx responses when `options.simple` is `true` (default). Please update your `transform` functions to also cover the transformation of non-2xx responses. To get the old behavior you may add `if (!(/^2/.test('' + response.statusCode))) { return resolveWithFullResponse ? response : body; }` to the first line of your `transform` functions that are used for requests with `options.simple === true`. However, you may prefer updating your `transform` functions to being able to transform 2xx as well as non-2xx responses because this decouples their implementation from the use of the `simple` option when doing requests.
- If a transform operation throws an error, the request will be rejected with a `TransformError`. Its `cause` attribute contains the error thrown by the transform operation. Previously, the request was rejected directly with the error thrown by the transform operation. Wrapping it into a `TransformError` makes the error handling easier.
2. Bluebird got updated from v2 to v3. This won't make a difference for most use cases. However, if you use advanced Promise chains starting with the Promise returned by Request-Promise, please check [Bluebird's new features and changes](http://bluebirdjs.com/docs/new-in-bluebird-3.html).
---
## Installation
This module is installed via npm:
```
npm install --save request
npm install --save request-promise
```
`request` is defined as a peer-dependency and thus has to be installed separately.
## Cheat Sheet
``` js
var rp = require('request-promise');
```
Since `request-promise` wraps around `request` everything that works with `request` also works with `request-promise`. Also check out the [`request` docs](https://github.com/request/request) for more examples.
### Crawl a webpage
``` js
rp('http://www.google.com')
.then(function (htmlString) {
// Process html...
})
.catch(function (err) {
// Crawling failed...
});
```
### Crawl a webpage better
``` js
var cheerio = require('cheerio'); // Basically jQuery for node.js
var options = {
uri: 'http://www.google.com',
transform: function (body) {
return cheerio.load(body);
}
};
rp(options)
.then(function ($) {
// Process html like you would with jQuery...
})
.catch(function (err) {
// Crawling failed or Cheerio choked...
});
```
### GET something from a JSON REST API
``` js
var options = {
uri: 'https://api.github.com/user/repos',
qs: {
access_token: 'xxxxx xxxxx' // -> uri + '?access_token=xxxxx%20xxxxx'
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
rp(options)
.then(function (repos) {
console.log('User has %d repos', repos.length);
})
.catch(function (err) {
// API call failed...
});
```
### POST data to a JSON REST API
Set `option.body` to your data and `json: true` to encode the body as JSON. See below for HTML forms.
``` js
var options = {
method: 'POST',
uri: 'http://api.posttestserver.com/post',
body: {
some: 'payload'
},
json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(function (parsedBody) {
// POST succeeded...
})
.catch(function (err) {
// POST failed...
});
```
### POST like HTML forms do
Set `option.form` to your data to encode the body the same way as HTML forms do.
``` js
var options = {
method: 'POST',
uri: 'http://posttestserver.com/post.php',
form: {
some: 'payload' // Will be urlencoded
},
headers: {
/* 'content-type': 'application/x-www-form-urlencoded' */ // Is set automatically
}
};
rp(options)
.then(function (body) {
// POST succeeded...
})
.catch(function (err) {
// POST failed...
});
```
### Include a cookie
``` js
var tough = require('tough-cookie');
// Easy creation of the cookie - see tough-cookie docs for details
let cookie = new tough.Cookie({
key: "some_key",
value: "some_value",
domain: 'api.mydomain.com',
httpOnly: true,
maxAge: 31536000
});
// Put cookie in an jar which can be used across multiple requests
var cookiejar = rp.jar();
cookiejar.setCookie(cookie, 'https://api.mydomain.com');
// ...all requests to https://api.mydomain.com will include the cookie
var options = {
uri: 'https://api.mydomain.com/...',
jar: cookiejar // Tells rp to include cookies in jar that match uri
};
rp(options)
.then(function (body) {
// Request succeeded...
})
.catch(function (err) {
// Request failed...
});
```
### Get the full response instead of just the body
``` js
var options = {
method: 'DELETE',
uri: 'http://my-server/path/to/resource/1234',
resolveWithFullResponse: true // <--- <--- <--- <---
};
rp(options)
.then(function (response) {
console.log("DELETE succeeded with status %d", response.statusCode);
})
.catch(function (err) {
// Delete failed...
});
```
### Get a rejection only if the request failed for technical reasons
``` js
var options = {
uri: 'http://www.google.com/this-page-does-not-exist.html',
simple: false // <--- <--- <--- <---
};
rp(options)
.then(function (body) {
// Request succeeded but might as well be a 404
// Usually combined with resolveWithFullResponse = true to check response.statusCode
})
.catch(function (err) {
// Request failed due to technical reasons...
});
```
---
**For more options checkout the [Request docs](https://github.com/request/request#requestoptions-callback).**
---
## API in Detail
Consider Request-Promise being:
- A Request object
- With an [identical API](https://github.com/request/request): `require('request-promise') == require('request')` so to say
- However, **STREAMING THE RESPONSE** (e.g. `.pipe(...)`) is **DISCOURAGED** because Request-Promise would grow the memory footprint for large requests unnecessarily high. Use the original Request library for that. You can use both libraries in the same project.
- Plus some methods on a request call object:
- `rp(...).then(...)` or e.g. `rp.post(...).then(...)` which turn `rp(...)` and `rp.post(...)` into promises
- `rp(...).catch(...)` or e.g. `rp.del(...).catch(...)` which is the same method as provided by Bluebird promises
- `rp(...).finally(...)` or e.g. `rp.put(...).finally(...)` which is the same method as provided by Bluebird promises
- `rp(...).cancel()` or e.g. `rp.get(...).cancel()` which cancels the request
- `rp(...).promise()` or e.g. `rp.head(...).promise()` which returns the underlying promise so you can access the full [Bluebird API](https://github.com/petkaantonov/bluebird/blob/master/API.md)
- Plus some additional options:
- `simple = true` which is a boolean to set whether status codes other than 2xx should also reject the promise
- `resolveWithFullResponse = false` which is a boolean to set whether the promise should be resolved with the full response or just the response body
- `transform` which takes a function to transform the response into a custom value with which the promise is resolved
- `transform2xxOnly = false` which is a boolean to set whether the transform function is applied to all responses or only to those with a 2xx status code
The objects returned by request calls like `rp(...)` or e.g. `rp.post(...)` are regular Promises/A+ compliant promises and can be assimilated by any compatible promise library.
The methods `.then(...)`, `.catch(...)`, and `.finally(...)` - which you can call on the request call objects - return a full-fledged Bluebird promise. That means you have the full [Bluebird API](https://github.com/petkaantonov/bluebird/blob/master/API.md) available for further chaining. E.g.: `rp(...).then(...).spread(...)` If, however, you need a method other than `.then(...)`, `.catch(...)`, or `.finally(...)` to be **FIRST** in the chain, use `.promise()`: `rp(...).promise().bind(...).then(...)`
### .then(onFulfilled, onRejected)
``` js
// As a Request user you would write:
var request = require('request');
request('http://google.com', function (err, response, body) {
if (err) {
handleError({ error: err, response: response, ... });
} else if (!(/^2/.test('' + response.statusCode))) { // Status Codes other than 2xx
handleError({ error: body, response: response, ... });
} else {
process(body);
}
});
// As a Request-Promise user you can now write the equivalent code:
var rp = require('request-promise');
rp('http://google.com')
.then(process, handleError);
```
``` js
// The same is available for all http method shortcuts:
request.post('http://example.com/api', function (err, response, body) { ... });
rp.post('http://example.com/api').then(...);
```
### .catch(onRejected)
``` js
rp('http://google.com')
.catch(handleError);
// ... is syntactical sugar for:
rp('http://google.com')
.then(null, handleError);
// However, this:
rp('http://google.com')
.then(process)
.catch(handleError);
// ... is safer than:
rp('http://google.com')
.then(process, handleError);
```
For more info on `.then(process).catch(handleError)` versus `.then(process, handleError)`, see Bluebird docs on [promise anti-patterns](http://bluebirdjs.com/docs/anti-patterns.html#the-.then).
### .finally(onFinished)
``` js
rp('http://google.com')
.finally(function () {
// This is called after the request finishes either successful or not successful.
});
```
### .cancel()
This method cancels the request using [Bluebird's cancellation feature](http://bluebirdjs.com/docs/api/cancellation.html).
When `.cancel()` is called:
- the promise will neither be resolved nor rejected and
- the request is [aborted](https://nodejs.org/dist/latest-v6.x/docs/api/http.html#http_request_abort).
### .promise() - For advanced use cases
In order to not pollute the Request call objects with the methods of the underlying Bluebird promise, only `.then(...)`, `.catch(...)`, and `.finally(...)` were exposed to cover most use cases. The effect is that any methods of a Bluebird promise other than `.then(...)`, `.catch(...)`, or `.finally(...)` cannot be used as the **FIRST** method in the promise chain:
``` js
// This works:
rp('http://google.com').then(function () { ... });
rp('http://google.com').catch(function () { ... });
// This works as well since additional methods are only used AFTER the FIRST call in the chain:
rp('http://google.com').then(function () { ... }).spread(function () { ... });
rp('http://google.com').catch(function () { ... }).error(function () { ... });
// Using additional methods as the FIRST call in the chain does not work:
// rp('http://google.com').bind(this).then(function () { ... });
// Use .promise() in these cases:
rp('http://google.com').promise().bind(this).then(function () { ... });
```
### Fulfilled promises and the `resolveWithFullResponse` option
``` js
// Per default the body is passed to the fulfillment handler:
rp('http://google.com')
.then(function (body) {
// Process the html of the Google web page...
});
// The resolveWithFullResponse options allows to pass the full response:
rp({ uri: 'http://google.com', resolveWithFullResponse: true })
.then(function (response) {
// Access response.statusCode, response.body etc.
});
```
### Rejected promises and the `simple` option
``` js
// The rejection handler is called with a reason object...
rp('http://google.com')
.catch(function (reason) {
// Handle failed request...
});
// ... and would be equivalent to this Request-only implementation:
var options = { uri: 'http://google.com' };
request(options, function (err, response, body) {
var reason;
if (err) {
reason = {
cause: err,
error: err,
options: options,
response: response
};
} else if (!(/^2/.test('' + response.statusCode))) { // Status Codes other than 2xx
reason = {
statusCode: response.statusCode,
error: body,
options: options,
response: response
};
}
if (reason) {
// Handle failed request...
}
});
// If you pass the simple option as false...
rp({ uri: 'http://google.com', simple: false })
.catch(function (reason) {
// Handle failed request...
});
// ... the equivalent Request-only code would be:
request(options, function (err, response, body) {
if (err) {
var reason = {
cause: err,
error: err,
options: options,
response: response
};
// Handle failed request...
}
});
// E.g. a 404 would now fulfill the promise.
// Combine it with resolveWithFullResponse = true to check the status code in the fulfillment handler.
```
With version 0.4 the reason objects became Error objects with identical properties to ensure backwards compatibility. These new Error types allow targeted catch blocks:
``` js
var errors = require('request-promise/errors');
rp('http://google.com')
.catch(errors.StatusCodeError, function (reason) {
// The server responded with a status codes other than 2xx.
// Check reason.statusCode
})
.catch(errors.RequestError, function (reason) {
// The request failed due to technical reasons.
// reason.cause is the Error object Request would pass into a callback.
});
```
### The `transform` function
You can pass a function to `options.transform` to generate a custom fulfillment value when the promise gets resolved.
``` js
// Just for fun you could reverse the response body:
var options = {
uri: 'http://google.com',
transform: function (body, response, resolveWithFullResponse) {
return body.split('').reverse().join('');
}
};
rp(options)
.then(function (reversedBody) {
// ;D
});
// However, you could also do something useful:
var $ = require('cheerio'); // Basically jQuery for node.js
function autoParse(body, response, resolveWithFullResponse) {
// FIXME: The content type string could contain additional values like the charset.
// Consider using the `content-type` library for a robust comparison.
if (response.headers['content-type'] === 'application/json') {
return JSON.parse(body);
} else if (response.headers['content-type'] === 'text/html') {
return $.load(body);
} else {
return body;
}
}
options.transform = autoParse;
rp(options)
.then(function (autoParsedBody) {
// :)
});
// You can go one step further and set the transform as the default:
var rpap = rp.defaults({ transform: autoParse });
rpap('http://google.com')
.then(function (autoParsedBody) {
// :)
});
rpap('http://echojs.com')
.then(function (autoParsedBody) {
// =)
});
```
The third `resolveWithFullResponse` parameter of the transform function is equivalent to the option passed with the request. This allows to distinguish whether just the transformed body or the whole response shall be returned by the transform function:
``` js
function reverseBody(body, response, resolveWithFullResponse) {
response.body = response.body.split('').reverse().join('');
return resolveWithFullResponse ? response : response.body;
}
```
As of Request-Promise v3 the transform function is ALWAYS executed for non-2xx responses. When `options.simple` is set to `true` (default) then non-2xx responses are rejected with a `StatusCodeError`. In this case the error contains the transformed response:
``` js
var options = {
uri: 'http://the-server.com/will-return/404',
simple: true,
transform: function (body, response, resolveWithFullResponse) { /* ... */ }
};
rp(options)
.catch(errors.StatusCodeError, function (reason) {
// reason.response is the transformed response
});
```
You may set `options.transform2xxOnly = true` to only execute the transform function for responses with a 2xx status code. For other status codes &ndash; independent of any other settings, e.g. `options.simple` &ndash; the transform function is not executed.
#### Error handling
If the transform operation fails (throws an error) the request will be rejected with a `TransformError`:
``` js
var errors = require('request-promise/errors');
var options = {
uri: 'http://google.com',
transform: function (body, response, resolveWithFullResponse) {
throw new Error('Transform failed!');
}
};
rp(options)
.catch(errors.TransformError, function (reason) {
console.log(reason.cause.message); // => Transform failed!
// reason.response is the original response for which the transform operation failed
});
```
## Experimental Support for Continuation Local Storage
Continuation Local Storage is no longer supported. However, you [can get back the support](https://github.com/request/request-promise/wiki/Getting-Back-Support-for-Continuation-Local-Storage) by using `request-promise-any`.
## Debugging
The ways to debug the operation of Request-Promise are the same [as described](https://github.com/request/request#debugging) for Request. These are:
1. Launch the node process like `NODE_DEBUG=request node script.js` (`lib,request,otherlib` works too).
2. Set `require('request-promise').debug = true` at any time (this does the same thing as #1).
3. Use the [request-debug module](https://github.com/nylen/request-debug) to view request and response headers and bodies. Instrument Request-Promise with `require('request-debug')(rp);`.
## Mocking Request-Promise
Usually you want to mock the whole request function which is returned by `require('request-promise')`. This is not possible by using a mocking library like [sinon.js](http://sinonjs.org) alone. What you need is a library that ties into the module loader and makes sure that your mock is returned whenever the tested code is calling `require('request-promise')`. [Mockery](https://github.com/mfncooper/mockery) is one of such libraries.
@florianschmidt1994 kindly shared his solution:
```javascript
before(function (done) {
var filename = "fileForResponse";
mockery.enable({
warnOnReplace: false,
warnOnUnregistered: false,
useCleanCache: true
});
mockery.registerMock('request-promise', function () {
var response = fs.readFileSync(__dirname + '/data/' + filename, 'utf8');
return Bluebird.resolve(response.trim());
});
done();
});
after(function (done) {
mockery.disable();
mockery.deregisterAll();
done();
});
describe('custom test case', function () {
// Test some function/module/... which uses request-promise
// and it will always receive the predefined "fileForResponse" as data, e.g.:
var rp = require('request-promise');
rp(...).then(function(data) {
// ➞ data is what is in fileForResponse
});
});
```
Based on that you may now build a more sophisticated mock. [Sinon.js](http://sinonjs.org) may be of help as well.
## Contributing
To set up your development environment:
1. clone the repo to your desktop,
2. in the shell `cd` to the main folder,
3. hit `npm install`,
4. hit `npm install gulp -g` if you haven't installed gulp globally yet, and
5. run `gulp dev`. (Or run `node ./node_modules/.bin/gulp dev` if you don't want to install gulp globally.)
`gulp dev` watches all source files and if you save some changes it will lint the code and execute all tests. The test coverage report can be viewed from `./coverage/lcov-report/index.html`.
If you want to debug a test you should use `gulp test-without-coverage` to run all tests without obscuring the code by the test coverage instrumentation.
## Change History
- v4.2.1 (2017-05-07)
- Fix that allows to use `tough-cookie` for cookie creation
*(Thanks to @ScottyMJacobson for reporting [issue #183](https://github.com/request/request-promise/issues/183))*
- Added [cookie handling example](https://github.com/request/request-promise#include-a-cookie) to the cheat sheet
*(Thanks to @chovy and @ProfessorTom for [asking for it](https://github.com/request/request-promise/issues/79))*
- v4.2.0 (2017-03-16)
- Updated `bluebird` to v3.5
*(Thanks to @acinader for [pull request #181](https://github.com/request/request-promise/pull/181))*
- v4.1.1 (2016-08-08)
- Renamed internally used package `@request/promise-core` to `request-promise-core` because there where [too](https://github.com/request/request-promise/issues/137) [many](https://github.com/request/request-promise/issues/141) issues with the scoped package name
*(Thanks to @cabrinoob, @crazy4groovy, @dsandor, @KpjComp, @lorenwest, @Reisyukaku, @tehChromic, @todd for providing helpful information.)*
- v4.1.0 (2016-07-30)
- Added cancellation support
*(Thanks to @not-an-aardvark for [pull request #123](https://github.com/request/request-promise/pull/123))*
- v4.0.2 (2016-07-18)
- Fix for using with module bundlers like Webpack and Browserify
- v4.0.1 (2016-07-17)
- Fixed `@request/promise-core` version for safer versioning
- v4.0.0 (2016-07-15)
- **Breaking Change**: `request` is declared as a peer dependency which has to be installed separately by the user now
- **Breaking Change**: Dropped support for Continuation Local Storage since [`request-promise-any`](https://github.com/request/request-promise-any) can be [used](https://github.com/request/request-promise/wiki/Getting-Back-Support-for-Continuation-Local-Storage) for that now
- Introduced the `transform2xxOnly` option to ease the breaking change regarding the new `transform` handling in v3.0.0
*(Thanks to @stevage for pointing out the effect of the breaking change in [issue #131](https://github.com/request/request-promise/issues/131))*
- Resolved issues [#65](https://github.com/request/request-promise/issues/65) and [#71](https://github.com/request/request-promise/issues/71) by publishing nearly identical libraries to support other Promise implementations: [`request-promise-native`](https://github.com/request/request-promise-native) and [`request-promise-any`](https://github.com/request/request-promise-any)
*(Thanks to @benjamingr, @eilgin, @gillesdemey, @hildjj, @iggycoloma, @jonathanong, @knpwrs, @MarkHerhold, @massimocode, @mikeal, @niftylettuce, @raitucarp, @sherdeadlock, @tonylukasavage, and @vgoloviznin for the valuable discussions!)*
- Relicensed this library with the ISC license
- v3.0.0 (2016-04-16)
- **Breaking Change**: Overhauled the handling of the `transform` function
*(Thanks to @Limess for explaining the need in [issue #86](https://github.com/request/request-promise/issues/86))*
- **Breaking Change**: Updated `bluebird` to v3
*(Thanks to @BrandonSmith for [pull request #103](https://github.com/request/request-promise/pull/103))*
- Improved `StatusCodeError.message`
- Updated `lodash` to v4.6
- Improved README in regard to `.catch(...)` best practice
*(Thanks to @RebootJeff for [pull request #98](https://github.com/request/request-promise/pull/98))*
- v2.0.1 (2016-02-17)
- Updated `lodash` to v4
*(Thanks to @ratson for [pull request #94](https://github.com/request/request-promise/pull/94))*
- v2.0.0 (2016-01-12)
- **Breaking Change**: Removed explicit `cls-bluebird` dependency which has to be installed by the user now
*(Thanks to @hildjj for his [pull request #75](https://github.com/request/request-promise/pull/75))*
- `npm shrinkwrap` now works for `npm@3` users who don't use `continuation-local-storage`
*(Thanks to @toboid and @rstacruz for reporting the issue in [issue #70](https://github.com/request/request-promise/issues/70) and [issue #82](https://github.com/request/request-promise/issues/82))*
- v1.0.2 (2015-10-22)
- Removed `continuation-local-storage` from peer dependencies as it was unnecessary
*(Thanks to @mrhyde for working on a better solution discussed in [issue #70](https://github.com/request/request-promise/issues/70))*
- v1.0.1 (2015-10-14)
- Fixed a npm warning by marking `continuation-local-storage` as a peer dependency
- v1.0.0 (2015-10-11)
- **Breaking Change**: Some errors that were previously thrown synchronously - e.g. for wrong input parameters - are now passed to the rejected promise instead
*(Thanks to @josnidhin for suggesting that in [issue #43](https://github.com/request/request-promise/issues/43))*
- **Breaking Change**: Request-Promise does not load its own Bluebird prototype anymore. If you use Bluebird in your project and altered the prototype then Request-Promise may use your altered Bluebird prototype internally.
- For HEAD requests the headers instead of an empty body is returned (unless `resolveWithFullResponse = true` is used)
*(Thanks to @zcei for proposing the change in [issue #58](https://github.com/request/request-promise/issues/58))*
- Extended `transform` function by a third `resolveWithFullResponse` parameter
- Added experimental support for continuation local storage
*(Thanks to @silverbp preparing this in [issue #64](https://github.com/request/request-promise/issues/64))*
- Added node.js 4 to the Travis CI build
- Updated the README
*(Thanks to many people for their feedback in issues [#55](https://github.com/request/request-promise/issues/55) and [#59](https://github.com/request/request-promise/issues/59))*
- v0.4.3 (2015-07-27)
- Reduced overhead by just requiring used lodash functions instead of the whole lodash library
*(Thanks to @luanmuniz for [pull request #54](https://github.com/request/request-promise/pull/54))*
- Updated dependencies
- v0.4.2 (2015-04-12)
- Updated dependencies
- v0.4.1 (2015-03-20)
- Improved Error types to work in browsers without v8 engine
*(Thanks to @nodiis for [pull request #40](https://github.com/request/request-promise/pull/40))*
- v0.4.0 (2015-02-08)
- Introduced Error types used for the reject reasons (See last part [this section](#rejected-promises-and-the-simple-option))
*(Thanks to @jakecraige for starting the discussion in [issue #38](https://github.com/request/request-promise/issues/38))*
- **Minor Breaking Change:** The reject reason objects became actual Error objects. However, `typeof reason === 'object'` still holds true and the error objects have the same properties as the previous reason objects. If the reject handler only accesses the properties on the reason object - which is usually the case - no migration is required.
- Added io.js and node.js 0.12 to the Travis CI build
- v0.3.3 (2015-01-19)
- Fixed handling possibly unhandled rejections to work with the latest version of Bluebird
*(Thanks to @slang800 for reporting this in [issue #36](https://github.com/request/request-promise/issues/36))*
- v0.3.2 (2014-11-17)
- Exposed `.finally(...)` to allow using it as the first method in the promise chain
*(Thanks to @hjpbarcelos for his [pull request #28](https://github.com/request/request-promise/pull/28))*
- v0.3.1 (2014-11-11)
- Added the `.promise()` method for advanced Bluebird API usage
*(Thanks to @devo-tox for his feedback in [issue #27](https://github.com/request/request-promise/issues/27))*
- v0.3.0 (2014-11-10)
- Carefully rewritten from scratch to make Request-Promise a drop-in replacement for Request
## License (ISC)
In case you never heard about the [ISC license](http://en.wikipedia.org/wiki/ISC_license) it is functionally equivalent to the MIT license.
See the [LICENSE file](LICENSE) for details.
\ No newline at end of file
'use strict';
module.exports = require('request-promise-core/errors');
'use strict';
var Bluebird = require('bluebird').getNewLibraryCopy(),
configure = require('request-promise-core/configure/request2'),
stealthyRequire = require('stealthy-require');
try {
// Load Request freshly - so that users can require an unaltered request instance!
var request = stealthyRequire(require.cache, function () {
return require('request');
},
function () {
require('tough-cookie');
}, module);
} catch (err) {
/* istanbul ignore next */
var EOL = require('os').EOL;
/* istanbul ignore next */
console.error(EOL + '###' + EOL + '### The "request" library is not installed automatically anymore.' + EOL + '### But required by "request-promise".' + EOL + '###' + EOL + '### npm install request --save' + EOL + '###' + EOL);
/* istanbul ignore next */
throw err;
}
Bluebird.config({cancellation: true});
configure({
request: request,
PromiseImpl: Bluebird,
expose: [
'then',
'catch',
'finally',
'cancel',
'promise'
],
constructorMixin: function (resolve, reject, onCancel) {
var self = this;
onCancel(function () {
self.abort();
});
}
});
request.bindCLS = function RP$bindCLS() {
throw new Error('CLS support was dropped. To get it back read: https://github.com/request/request-promise/wiki/Getting-Back-Support-for-Continuation-Local-Storage');
};
module.exports = request;
../../_bluebird@3.5.0@bluebird
\ No newline at end of file
../../_request-promise-core@1.1.1@request-promise-core
\ No newline at end of file
../../_stealthy-require@1.1.1@stealthy-require
\ No newline at end of file
../../_tough-cookie@2.3.2@tough-cookie
\ No newline at end of file
{
"name": "request-promise",
"version": "4.2.1",
"description": "The simplified HTTP request client 'request' with Promise support. Powered by Bluebird.",
"keywords": [
"xhr",
"http",
"https",
"promise",
"request",
"then",
"thenable",
"bluebird"
],
"main": "./lib/rp.js",
"scripts": {
"test": "./node_modules/.bin/gulp ci",
"test-publish": "./node_modules/.bin/gulp ci-no-cov",
"publish-please": "publish-please",
"prepublish": "publish-please guard"
},
"repository": {
"type": "git",
"url": "git+https://github.com/request/request-promise.git"
},
"author": "Nicolai Kamenzky (https://github.com/analog-nico)",
"license": "ISC",
"bugs": {
"url": "https://github.com/request/request-promise/issues"
},
"homepage": "https://github.com/request/request-promise#readme",
"engines": {
"node": ">=0.10.0"
},
"dependencies": {
"request-promise-core": "1.1.1",
"bluebird": "^3.5.0",
"stealthy-require": "^1.1.0",
"tough-cookie": ">=2.3.0"
},
"peerDependencies": {
"request": "^2.34"
},
"devDependencies": {
"body-parser": "~1.15.2",
"chai": "~3.5.0",
"chalk": "~1.1.3",
"gulp": "~3.9.1",
"gulp-coveralls": "~0.1.4",
"gulp-eslint": "~2.1.0",
"gulp-istanbul": "~1.0.0",
"gulp-mocha": "~2.2.0",
"lodash": "~4.13.1",
"publish-please": "~2.1.4",
"request": "^2.34.0",
"rimraf": "~2.5.3",
"run-sequence": "~1.2.2"
},
"_from": "request-promise@4.2.1",
"_resolved": "http://registry.npm.taobao.org/request-promise/download/request-promise-4.2.1.tgz"
}
\ No newline at end of file
/.idea/
/coverage/
/test/
/.editorconfig
/.eslintrc.json
/.gitignore
/.publishrc
/.travis.yml
/gulpfile.js
.DS_Store
npm-debug.log
\ No newline at end of file
Mon Aug 07 2017 15:31:48 GMT+0800 (CST)
\ No newline at end of file
ISC License
Copyright (c) 2017, Nicolai Kamenzky and contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
\ No newline at end of file
# Stealthy-Require
[![Build Status](https://img.shields.io/travis/analog-nico/stealthy-require/master.svg?style=flat-square)](https://travis-ci.org/analog-nico/stealthy-require)
[![Coverage Status](https://img.shields.io/coveralls/analog-nico/stealthy-require.svg?style=flat-square)](https://coveralls.io/r/analog-nico/stealthy-require)
[![Dependency Status](https://img.shields.io/david/analog-nico/stealthy-require.svg?style=flat-square)](https://david-dm.org/analog-nico/stealthy-require)
This is probably the closest you can currently get to require something in node.js with completely bypassing the require cache.
`stealthy-require` works like this:
1. It clears the require cache.
2. It calls a callback in which you require your module(s) without the cache kicking in.
3. It clears the cache again and restores its old state.
The restrictions are:
- [Native modules cannot be required twice.](https://github.com/nodejs/node/issues/5016) Thus this module bypasses the require cache only for non-native (e.g. JS) modules.
- The require cache is only bypassed for all operations that happen synchronously when a module is required. If a module lazy loads another module at a later time that require call will not bypass the cache anymore.
This means you should have a close look at all internal require calls before you decide to use this library.
## Installation
[![NPM Stats](https://nodei.co/npm/stealthy-require.png?downloads=true)](https://npmjs.org/package/stealthy-require)
This is a module for node.js and is installed via npm:
``` bash
npm install stealthy-require --save
```
## Usage
Let's say you want to bypass the require cache for this require call:
``` js
var request = require('request');
```
With `stealthy-require` you can do that like this:
``` js
var stealthyRequire = require('stealthy-require');
var requestFresh = stealthyRequire(require.cache, function () {
return require('request');
});
```
The require cache is bypassed for the module you require (i.e. `request`) as well as all modules the module requires (i.e. `http` and many more).
Sometimes the require cache shall not be bypassed for specific modules. E.g. `request` is required but `tough-cookie` – on which `request` depends on – shall be required using the regular cache. For that you can pass two extra arguments to `stealthyRequire(...)`:
- A callback that requires the modules that shall be required without bypassing the cache
- The `module` variable
``` js
var stealthyRequire = require('stealthy-require');
var requestFresh = stealthyRequire(require.cache, function () {
return require('request');
},
function () {
require('tough-cookie'); // No return needed
// You can require multiple modules here
}, module);
```
## Usage with Module Bundlers
- [Webpack](https://webpack.github.io) works out-of-the-box like described in the [Usage section](#usage) above.
- [Browserify](http://browserify.org) does not expose `require.cache`. However, as of `browserify@13.0.1` the cache is passed as the 6th argument to CommonJS modules. Thus you can pass this argument instead:
``` js
// Tweak for Browserify - using arguments[5] instead of require.cache
var requestFresh = stealthyRequire(arguments[5], function () {
return require('request');
});
```
## Preventing a Memory Leak When Repeatedly Requiring Fresh Module Instances in Node.js
If you are using `stealthy-require` in node.js and repeatedly require fresh module instances the `module.children` array will hold all module instances which prevents unneeded instances to be garbage collected.
Assume your code calls `doSomething()` repeatedly.
``` js
var stealthyRequire = require('stealthy-require');
function doSomething() {
var freshInstance = stealthyRequire(require.cache, function () {
return require('some-module');
});
return freshInstance.calc();
}
```
After `doSomething()` returns `freshInstance` is not used anymore but won’t be garbage collected because `module.children` still holds a reference. The solution is to truncate `module.children` accordingly:
``` js
var stealthyRequire = require('stealthy-require');
function doSomething() {
var initialChildren = module.children.slice(); // Creates a shallow copy of the array
var freshInstance = stealthyRequire(require.cache, function () {
return require('some-module');
});
module.children = initialChildren;
return freshInstance.calc();
}
```
The `slice` operation removes all new `module.children` entries created during the `stealthyRequire(...)` call and thus `freshInstance` gets garbage collected after `doSomething()` returns.
## Technical Walkthrough
``` js
// 1. Load stealthy-require
var stealthyRequire = require('stealthy-require');
// This does nothing but loading the code.
// It has no side-effects like patching the module loader or anything.
// Any regular require works as always.
var request1 = require('request');
// 2. Call stealthyRequire with passing the require cache and a callback.
var requestFresh = stealthyRequire(require.cache, function () {
// 2a. Before this callback gets called the require cache is cleared.
// 2b. Any require taking place here takes place on a clean require cache.
// Since the require call is part of the user's code it also works with module bundlers.
return require('request');
// Anything returned here will be returned by stealthyRequire(...).
// 2c. After this callback gets called the require cache is
// - cleared again and
// - restored to its old state before step 2.
});
// Any regular require again works as always.
// In this case require returns the cached request module instance.
var request2 = require('request');
// And voilà:
request1 === request2 // -> true
request1 === requestFresh // -> false
```
## Contributing
To set up your development environment for `stealthy-require`:
1. Clone this repo to your desktop,
2. in the shell `cd` to the main folder,
3. hit `npm install`,
4. hit `npm install gulp -g` if you haven't installed gulp globally yet, and
5. run `gulp dev`. (Or run `node ./node_modules/.bin/gulp dev` if you don't want to install gulp globally.)
`gulp dev` watches all source files and if you save some changes it will lint the code and execute all tests. The test coverage report can be viewed from `./coverage/lcov-report/index.html`.
If you want to debug a test you should use `gulp test-without-coverage` to run all tests without obscuring the code by the test coverage instrumentation.
## Change History
- v1.1.1 (2017-05-08)
- Fix that stops `undefined` entries from appearing in `require.cache` *(Thanks to @jasperjn from reporting this in [issue #4](https://github.com/analog-nico/stealthy-require/issues/4))*
- v1.1.0 (2017-04-25)
- Added ability to disable bypassing the cache for certain modules *(Thanks to @novemberborn for suggesting this in [issue #3](https://github.com/analog-nico/stealthy-require/issues/3))*
- Added section in README about a [potential memory leak](#preventing-a-memory-leak-when-repeatedly-requiring-fresh-module-instances-in-nodejs) *(Thanks to @Flarna and @novemberborn for bringing that up in [issue #2](https://github.com/analog-nico/stealthy-require/issues/2))*
- Performance optimizations *(Thanks to @jcready for [pull request #1](https://github.com/analog-nico/stealthy-require/pull/1))*
- v1.0.0 (2016-07-18)
- **Breaking Change:** API completely changed. Please read the [Usage section](#usage) again.
- Redesigned library to support module bundlers like [Webpack](https://webpack.github.io) and [Browserify](http://browserify.org)
- v0.1.0 (2016-05-26)
- Initial version
## License (ISC)
In case you never heard about the [ISC license](http://en.wikipedia.org/wiki/ISC_license) it is functionally equivalent to the MIT license.
See the [LICENSE file](LICENSE) for details.
'use strict';
var isNative = /\.node$/;
function forEach(obj, callback) {
for ( var key in obj ) {
if (!Object.prototype.hasOwnProperty.call(obj, key)) {
continue;
}
callback(key);
}
}
function assign(target, source) {
forEach(source, function (key) {
target[key] = source[key];
});
return target;
}
function clearCache(requireCache) {
forEach(requireCache, function (resolvedPath) {
if (!isNative.test(resolvedPath)) {
delete requireCache[resolvedPath];
}
});
}
module.exports = function (requireCache, callback, callbackForModulesToKeep, module) {
var originalCache = assign({}, requireCache);
clearCache(requireCache);
if (callbackForModulesToKeep) {
var originalModuleChildren = module.children ? module.children.slice() : false; // Creates a shallow copy of module.children
callbackForModulesToKeep();
// Lists the cache entries made by callbackForModulesToKeep()
var modulesToKeep = [];
forEach(requireCache, function (key) {
modulesToKeep.push(key);
});
// Discards the modules required in callbackForModulesToKeep()
clearCache(requireCache);
if (module.children) { // Only true for node.js
module.children = originalModuleChildren; // Removes last references to modules required in callbackForModulesToKeep() -> No memory leak
}
// Takes the cache entries of the original cache in case the modules where required before
for ( var i = 0; i < modulesToKeep.length; i+=1 ) {
if (originalCache[modulesToKeep[i]]) {
requireCache[modulesToKeep[i]] = originalCache[modulesToKeep[i]];
}
}
}
var freshModule = callback();
var stealthCache = callbackForModulesToKeep ? assign({}, requireCache) : false;
clearCache(requireCache);
if (callbackForModulesToKeep) {
// In case modules to keep were required inside the stealthy require for the first time, copy them to the restored cache
for ( var k = 0; k < modulesToKeep.length; k+=1 ) {
if (stealthCache[modulesToKeep[k]]) {
requireCache[modulesToKeep[k]] = stealthCache[modulesToKeep[k]];
}
}
}
assign(requireCache, originalCache);
return freshModule;
};
{
"name": "stealthy-require",
"version": "1.1.1",
"description": "The closest you can get to require something with bypassing the require cache",
"keywords": [
"require",
"bypass",
"no",
"cache",
"fresh"
],
"main": "./lib/index.js",
"scripts": {
"test": "./node_modules/.bin/gulp ci",
"test-publish": "./node_modules/.bin/gulp ci-no-cov",
"publish-please": "publish-please",
"prepublish": "publish-please guard"
},
"repository": {
"type": "git",
"url": "git+https://github.com/analog-nico/stealthy-require.git"
},
"author": "Nicolai Kamenzky (https://github.com/analog-nico)",
"license": "ISC",
"bugs": {
"url": "https://github.com/analog-nico/stealthy-require/issues"
},
"homepage": "https://github.com/analog-nico/stealthy-require#readme",
"engines": {
"node": ">=0.10.0"
},
"dependencies": {},
"devDependencies": {
"bcrypt": "~1.0.2",
"browserify": "~14.3.0",
"chai": "~3.5.0",
"chalk": "~1.1.3",
"gulp": "~3.9.1",
"gulp-coveralls": "~0.1.4",
"gulp-eslint": "~2.1.0",
"gulp-istanbul": "~1.1.1",
"gulp-mocha": "~3.0.1",
"mkdirp": "~0.5.1",
"publish-please": "~2.3.1",
"rimraf": "~2.6.1",
"run-sequence": "~1.2.2",
"webpack": "~1.15.0"
},
"_from": "stealthy-require@1.1.1",
"_resolved": "http://registry.npm.taobao.org/stealthy-require/download/stealthy-require-1.1.1.tgz"
}
\ No newline at end of file
_pify@3.0.0@pify
\ No newline at end of file
_request-promise@4.2.1@request-promise
\ No newline at end of file
_request-promise-core@1.1.1@request-promise-core
\ No newline at end of file
_stealthy-require@1.1.1@stealthy-require
\ No newline at end of file
......@@ -7,6 +7,7 @@
"phantom": "^4.0.5",
"redis": "^2.7.1",
"request": "^2.81.0",
"request-promise": "^4.2.1",
"toml": "^2.3.2"
}
}
{"returncode":0,"message":"","result":{"rowcount":464,"pagesize":20,"pageindex":1,"list":[{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"302326\")'>孟</a><br/><span></span>","CustomerPhoneStr":"18337159943<br/>河南 郑州","OrderTypeStr":"订单<br/>私有","OrderStateStr":"订单未跟进","LeadTimeStr":"2017-08-07 20:00:23","LicenseCityStr":"河南 郑州 ","SpecNameStr":"大迈X5 2017款 超值版 1.6L 手动时尚型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('302326')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('18337159943')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"302320\")'>杨光亮</a><br/><span></span>","CustomerPhoneStr":"13255967771<br/>河南 郑州","OrderTypeStr":"订单<br/>私有","OrderStateStr":"订单未跟进","LeadTimeStr":"2017-08-07 19:23:18","LicenseCityStr":"河南 郑州 ","SpecNameStr":"芝麻 2017款 标准型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('302320')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('13255967771')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"302314\")'>王路杨</a><br/><span></span>","CustomerPhoneStr":"17694836173<br/> ","OrderTypeStr":"订单<br/>公共","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-07 18:40:51","LicenseCityStr":"河南 濮阳 南乐","SpecNameStr":"大迈X7 2017款 1.5T 手动精英型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('302314')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('17694836173')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"302286\")'>魏保平</a><br/><span></span>","CustomerPhoneStr":"15539293131<br/>河南 鹤壁","OrderTypeStr":"订单<br/>公共","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-07 17:11:46","LicenseCityStr":"河南 鹤壁 ","SpecNameStr":"大迈X7 2017款 1.8T 自动尊贵型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('302286')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('15539293131')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"302275\")'>张金鹤</a><br/><span></span>","CustomerPhoneStr":"13938410632<br/>河南 郑州","OrderTypeStr":"订单<br/>私有","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-07 16:44:51","LicenseCityStr":"河南 郑州 ","SpecNameStr":"大迈X5 2017款 升级版 1.5T CVT知县型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('302275')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('13938410632')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"302260\")'>王自辉</a><br/><span></span>","CustomerPhoneStr":"17698936048<br/> ","OrderTypeStr":"订单<br/>私有","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-07 15:58:42","LicenseCityStr":"河南 郑州 ","SpecNameStr":"大迈X5 2017款 超值版 1.6L 手动时尚型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('302260')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('17698936048')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"302260\")'>王自辉</a><br/><span></span>","CustomerPhoneStr":"17698936048<br/> ","OrderTypeStr":"订单<br/>私有","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-07 15:57:51","LicenseCityStr":"河南 郑州 ","SpecNameStr":"大迈X5 2017款 升级版 1.5T 手动精英型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('302260')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('17698936048')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"302120\")'>卢胜军</a><br/><span></span>","CustomerPhoneStr":"15837193308<br/>河南 郑州","OrderTypeStr":"订单<br/>私有","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-07 10:23:31","LicenseCityStr":"河南 郑州 ","SpecNameStr":"大迈X5 2017款 升级版 1.5T 手动豪华型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('302120')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('15837193308')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"287672\")'>宋永红</a><br/><span></span>","CustomerPhoneStr":"13526859861<br/>河南 郑州","OrderTypeStr":"订单<br/>私有","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-07 01:21:27","LicenseCityStr":"河南 郑州 ","SpecNameStr":"大迈X5 2017款 超值版 1.6L 手动舒适型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('287672')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('13526859861')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"302047\")'>许杰</a><br/><span></span>","CustomerPhoneStr":"18338934911<br/>河南 新乡","OrderTypeStr":"订单<br/>私有","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-06 19:14:13","LicenseCityStr":"河南 郑州 ","SpecNameStr":"大迈X7 2017款 1.8T 自动豪华型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('302047')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('18338934911')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"302040\")'>陈宝</a><br/><span></span>","CustomerPhoneStr":"15539976386<br/>河南 南阳","OrderTypeStr":"订单<br/>公共","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-06 18:30:51","LicenseCityStr":"河南 南阳 ","SpecNameStr":"芝麻 2017款 标准型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('302040')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('15539976386')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"302017\")'>刘</a><br/><span></span>","CustomerPhoneStr":"18738184599<br/>河南 郑州","OrderTypeStr":"订单<br/>私有","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-06 17:07:45","LicenseCityStr":"河南 郑州 ","SpecNameStr":"大迈X7 2017款 1.5T 手动精英型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('302017')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('18738184599')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"301975\")'>王先生</a><br/><span></span>","CustomerPhoneStr":"15839031935<br/>河南 商丘","OrderTypeStr":"订单<br/>私有","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-06 14:33:54","LicenseCityStr":"河南 郑州 ","SpecNameStr":"大迈X5 2017款 超值版 1.6L 手动舒适型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('301975')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('15839031935')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"301897\")'>何万斗</a><br/><span></span>","CustomerPhoneStr":"18804512228<br/>黑龙江 哈尔滨","OrderTypeStr":"订单<br/>私有","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-06 08:58:50","LicenseCityStr":"河南 郑州 ","SpecNameStr":"大迈X7 2017款 1.5T 手动精英型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('301897')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('18804512228')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"301792\")'>刘淼</a><br/><span></span>","CustomerPhoneStr":"18736088477<br/>河南 郑州","OrderTypeStr":"订单<br/>私有","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-05 15:10:37","LicenseCityStr":"河南 郑州 ","SpecNameStr":"大迈X7 2017款 1.8T 自动豪华型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('301792')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('18736088477')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"301755\")'>谭帅兵</a><br/><span></span>","CustomerPhoneStr":"18637578005<br/>河南 平顶山","OrderTypeStr":"订单<br/>私有","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-05 12:21:24","LicenseCityStr":"河南 郑州 ","SpecNameStr":"大迈X7 2017款 1.8T 手动豪华型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('301755')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('18637578005')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"301754\")'>刘诗诗</a><br/><span></span>","CustomerPhoneStr":"13541401319<br/>四川 宜宾","OrderTypeStr":"订单<br/>公共","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-05 12:20:50","LicenseCityStr":"河南 焦作 ","SpecNameStr":"芝麻 2017款 标准型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('301754')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('13541401319')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"301643\")'>张磊</a><br/><span></span>","CustomerPhoneStr":"13083612195<br/>河南 许昌","OrderTypeStr":"订单<br/>公共","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-04 21:21:06","LicenseCityStr":"河南 许昌 ","SpecNameStr":"大迈X7 2017款 1.8T 自动精英型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('301643')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('13083612195')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"301602\")'>张路</a><br/><span></span>","CustomerPhoneStr":"15093074734<br/>河南 郑州","OrderTypeStr":"订单<br/>私有","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-04 18:18:58","LicenseCityStr":"河南 郑州 ","SpecNameStr":"大迈X7 2017款 2.0T 自动至尊型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('301602')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('15093074734')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0},{"CustomerNameStr":"<a href='#' onclick='showCusDetailWithId(\"301590\")'>薛文豪</a><br/><span></span>","CustomerPhoneStr":"15838308815<br/>河南 郑州","OrderTypeStr":"订单<br/>私有","OrderStateStr":"订单已跟进","LeadTimeStr":"2017-08-04 17:18:21","LicenseCityStr":"河南 郑州 ","SpecNameStr":"大迈X5 2017款 升级版 1.5T CVT总督型","OperateStr":"<a class='mr5' href='javascript:void(0)' onclick=\"showCusDetailWithId('301590')\">详情</a><a class='mr5' href='javascript:void(0)' onclick=\"showLog('15838308815')\">日志</a>","SalesNameStr":"田淮蒲 18300683353","ProductNameStr":"车商汇","TaskName":null,"GetLeadDealerNameStr":"[4s]河南明志汽车大迈-众泰汽车金坛事业部店","UnitPriceStr":"","DealerId":0,"ReDealerId":0}]},"countInfo":"0条订单待分配、464条已获得线索。已获得线索中464条订单,0条400电话(其中0条未接起)。","ishavassign":1}
\ No newline at end of file
"<!DOCTYPE html>\r\n<html>\r\n<head>\r\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n <title>i车商-智能营销生态系统</title>\r\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\" />\r\n <meta name=\"renderer\" content=\"webkit\">\r\n <link href=\"//x.autoimg.cn/dealer/ics/20170725A/Content/frame.css?version=1201\" rel=\"stylesheet\" />\r\n <link href=\"//x.autoimg.cn/dealer/ics/20170725A/Content/sundry.css?version=1201\" rel=\"stylesheet\" />\r\n\r\n <link rel=\"stylesheet\" href=\"//x.autoimg.cn/dealer/ics/20170725A/Content/newics/css/base.min.css\" />\r\n <link rel=\"stylesheet\" href=\"//x.autoimg.cn/dealer/ics/20170725A/Content/newics/css/common.min.css\" />\r\n <link rel=\"stylesheet\" href=\"//x.autoimg.cn/dealer/ics/20170725A/Content/newics/css/blue_skin.min.css\" />\r\n \r\n</head>\r\n<body>\r\n<!--mini顶部 start-->\r\n<div class=\"ics_top\" data-baseurl=\"//x.autoimg.cn/dealer/ics/20170725A\" data-basedomin=\"\" data-loginuser=\"系统管理员|0\" data-app=\"dms\">\r\n\r\n</div>\r\n<!--mini顶部 end-->\r\n<!--主导航 start-->\r\n<ul class=\"ics_nav\"></ul>\r\n<!--主导航 end-->\r\n<!--侧导航 start-->\r\n<div class=\"ics_subnav\">\r\n\r\n</div>\r\n<!--侧导航 end-->\r\n<!--内容区 start-->\r\n\r\n<div class=\"ics_main\">\r\n \r\n\r\n\r\n<div class=\"m-alert mb10\">\r\n <div class=\"alert-con\">\r\n <span class=\"alert-link\"><a href=\"http://ics.autohome.com.cn/BSS/Else/Suggestion\">点此反馈</a></span>\r\n <i class=\"u-icon16 u-icon16-exc\"></i>\r\n <span>线索问题可电询4008-177-168,或使用意见反馈~</span>\r\n </div>\r\n</div>\r\n<div class=\"m-crumbs\"><span>按线索管理</span>&nbsp;&gt;&nbsp; 新车线索</div>\r\n<div class=\"g-con t-customerfollow ml20 mr20\">\r\n <div class=\"m-head\">\r\n <h2>新车线索</h2>\r\n </div>\r\n <div class=\"m-box mb10\">\r\n <div class=\"box-tit\">\r\n <input type=\"hidden\" id=\"hid_exportMaxDays\" value=\"92\" />\r\n <input type=\"hidden\" id=\"hid_Phone\" value=\"0\" />\r\n <input type=\"hidden\" id=\"hid_logUrl\" value=\"http://ics.autohome.com.cn/BSS/Dealershowlog/Index\">\r\n <input type=\"hidden\" id=\"hid_ParamData\" />\r\n <input type=\"hidden\" id=\"hid_ParamDealerId\" value=\"0\" />\r\n <input type=\"hidden\" id=\"hid_IsCPLCompany\" value=\"0\" />\r\n <div class=\"f-clear mb10\">\r\n <dl class=\"m-control m-control-inline\">\r\n <dt><select class=\"select mr5\" id=\"sltAreaType\"><option value=\"0\">客户地区:</option><option value=\"1\">上牌地区:</option></select></dt>\r\n <dd>\r\n <select class=\"select mr5\" id=\"sltProvince\">\r\n <option value=\"-2\">全部省份</option>\r\n <option value=\"410000\">河南</option>\r\n\r\n </select>\r\n <select class=\"select mr5\" id=\"sltCity\">\r\n <option value=\"-2\">全部城市</option>\r\n </select>\r\n </dd>\r\n </dl>\r\n <select id=\"sel_saler\" class=\"select mr5\">\r\n <option value=\"0\">全部 负责销售</option>\r\n <option value=\"624938\">陈岩</option>\r\n <option value=\"715610\">田淮蒲</option>\r\n </select>\r\n <select id=\"sel_Dealers\" class=\"select mr5\">\r\n <option value=\"0\">全部 店铺</option>\r\n <option value=\"2025277\">[4s]河南明志汽车大迈-众泰汽车金坛事业部店</option>\r\n </select>\r\n\r\n </div>\r\n <div class=\"f-clear mb10\">\r\n <dl class=\"m-control m-control-inline\">\r\n <dt>意向车型:</dt>\r\n <dd>\r\n <select id=\"sltFactoryId\" class=\"select mr5\">\r\n <option value=\"0\" factoryid=\"0\">全部车系</option>\r\n <option style=\"font-size:12px;font-weight:bold;color:red;\" value=\"-1\" factoryid=\"171\">众泰汽车</option>\r\n <option style=\"font-size:11px;font-weight:normal;\" value=\"3779\" factoryid=\"171\">&nbsp;&nbsp;&nbsp;&nbsp;芝麻</option>\r\n <option style=\"font-size:11px;font-weight:normal;\" value=\"3793\" factoryid=\"171\">&nbsp;&nbsp;&nbsp;&nbsp;大迈X5</option>\r\n <option style=\"font-size:11px;font-weight:normal;\" value=\"4092\" factoryid=\"171\">&nbsp;&nbsp;&nbsp;&nbsp;大迈X7</option>\r\n\r\n </select>\r\n <select id=\"sltSeriesId\" class=\"select mr5\">\r\n <option value=\"-1\">全部车型</option>\r\n </select>\r\n </dd>\r\n </dl>\r\n <dl class=\"m-control m-control-inline\">\r\n <dt>线索类型:</dt>\r\n <dd>\r\n <select id=\"sltOrderType\" class=\"select mr5\">\r\n <option value=\"-1\">全部</option>\r\n <option value=\"1\">订单</option>\r\n <option value=\"2\">400</option>\r\n </select>\r\n <select id=\"sltPriPub\" class=\"select mr5\">\r\n <option value=\"-1\">全部</option>\r\n <option value=\"0\">私有</option>\r\n <option value=\"1\">公共</option>\r\n </select>\r\n </dd>\r\n </dl>\r\n <dl class=\"m-control m-control-inline\">\r\n <dt>线索状态:</dt>\r\n <dd>\r\n <select id=\"sltOrderStatus\" class=\"select mr5\">\r\n <option value=\"-1\">全部</option>\r\n <option value=\"1\">订单待分配</option>\r\n <option value=\"2\">订单未跟进</option>\r\n <option value=\"3\">订单已跟进</option>\r\n <option value=\"4\">400成功接听</option>\r\n <option value=\"5\">400未接起</option>\r\n </select>\r\n </dd>\r\n </dl>\r\n <dl class=\"m-control m-control-inline\">\r\n <dt>商业产品:</dt>\r\n <dd>\r\n <select id=\"sltProduct\" class=\"select mr5\">\r\n <option value=\"0\">全部</option>\r\n <option value=\"100\">车商汇</option>\r\n <option value=\"1200\">品驾汇</option>\r\n <option value=\"1300\">看车团</option>\r\n </select>\r\n </dd>\r\n </dl>\r\n </div>\r\n <div class=\"f-clear mb15\">\r\n <div class=\"f-right\">\r\n <a class=\"u-btn u-btn-mini u-btn-small u-btn-orange\" id=\"divExport\" style=\"display: none\" href=\"javascript:void(0)\" onclick=\"exportData(this)\">导出EXCEL表格</a>\r\n\r\n </div>\r\n <div class=\"f-left\">\r\n <dl class=\"m-control m-control-inline\">\r\n <dt>线索获得时间:</dt>\r\n <dd>\r\n <input type=\"text\" id=\"StartTime\" name=\"StartTime\"\r\n minvalue=\" 2017.03.07\"\r\n class=\"u-input mr5\" value=\"\" readonly=\"readonly\"\r\n onclick=\"showCalendar('StartTime', 'y.mm.dd');\" />\r\n <i class=\"u-icon16 u-icon16-timer\" onclick=\"showCalendar('StartTime', 'y.mm.dd');\"></i>至\r\n <input type=\"text\" type=\"text\" id=\"EndTime\" name=\"EndTime\"\r\n minvalue=\" 2017.03.07\"\r\n class=\"u-input mr5\" value=\"\" readonly=\"readonly\"\r\n onclick=\"showCalendar('EndTime', 'y.mm.dd');\" />\r\n <i class=\"u-icon16 u-icon16-timer\" onclick=\"showCalendar('EndTime', 'y.mm.dd');\"></i>\r\n </dd>\r\n </dl>\r\n <dl class=\"m-control m-control-inline\">\r\n <dt>客户号码:</dt>\r\n <dd><input type=\"text\" id=\"CustomerPhone\" name=\"CustomerPhone\" class=\"input\" /></dd>\r\n </dl> \r\n\t\t\t\t\t<input type=\"hidden\" id=\"TaskName\" name=\"TaskName\" class=\"input\" />\r\n <dl class=\"m-control m-control-inline\">\r\n <dt></dt>\r\n <dd>\r\n <a class=\"u-btn u-btn-mini\" href=\"javascript:void(0)\" onclick=\"renderGrid(1)\">搜索</a>\r\n </dd>\r\n </dl>\r\n </div>\r\n </div>\r\n <div class=\"red\">搜索结果:<span id=\"CountInfo\"></span></div>\r\n\r\n </div>\r\n <div class=\"box-con\">\r\n <div class=\"m-table2 informationlist-data mb10\">\r\n <table id=\"MainTable\">\r\n <thead>\r\n <tr>\r\n <th width=\"7%\">客户姓名</th>\r\n <th width=\"7%\">客户号码</th>\r\n <th width=\"8%\">负责销售</th>\r\n <th width=\"10%\">归属店铺</th>\r\n <th width=\"7%\">线索类型</th>\r\n <th width=\"7%\">线索状态</th>\r\n <th width=\"10%\"><b class=\"j-wen\"><span class=\"vm\">线索获得时间</span><i class=\"u-icon12 u-icon12-wen\"></i></b></th>\r\n <th width=\"7%\">上牌地区</th>\r\n <th width=\"10%\">线索意向车型</th>\r\n <th width=\"8%\">商业产品来源</th>\r\n <th width=\"9%\">管理</th>\r\n </tr>\r\n </thead>\r\n <tbody data-bind=\"foreach: Data\">\r\n <tr>\r\n <td align=\"center\" data-bind=\"html:CustomerNameStr()\"></td>\r\n <td align=\"center\" data-bind=\"html:CustomerPhoneStr()\"></td>\r\n <td align=\"center\" data-bind=\"html:SalesNameStr()\"></td>\r\n <td align=\"center\" data-bind=\"html:GetLeadDealerNameStr()\"></td>\r\n <td align=\"center\" data-bind=\"html:OrderTypeStr()\"></td>\r\n <td align=\"center\" data-bind=\"html:OrderStateStr()\"></td>\r\n <td align=\"center\" data-bind=\"html:LeadTimeStr()\"></td>\r\n <td align=\"center\" data-bind=\"html:LicenseCityStr()\"></td>\r\n <td align=\"center\" data-bind=\"html:SpecNameStr()\"></td>\r\n <td align=\"center\" data-bind=\"html:ProductNameStr()\"></td>\r\n <td align=\"center\" data-bind=\"html:OperateStr()\"></td>\r\n </tr>\r\n\r\n </tbody>\r\n </table>\r\n </div>\r\n <!--翻页-->\r\n <div class=\"m-pagination mb20\">\r\n </div>\r\n <!--end 翻页-->\r\n <!--查询结果提示-->\r\n <div id=\"div_message\" class=\"m-alert mb10\" style=\"display:none;width:250px;margin-left:auto;margin-right:auto;\">\r\n <div class=\"alert-con\" style=\"margin-left:auto;margin-right:auto;text-align:center;\">\r\n <i class=\"u-icon16 u-icon16-exc\"></i>\r\n 结果提示!未查询到相关数据\r\n </div>\r\n </div>\r\n\r\n </div>\r\n\r\n <!-- 弹框html代码 -->\r\n <div class=\"layer-bd\" style=\"display:none;\">\r\n <input type=\"hidden\" id=\"hid_OrderID\" value=\"\" />\r\n <div class=\"m-table4\">\r\n\r\n <!--展示信息-->\r\n <table>\r\n <tr>\r\n <td style=\"width:100px\" align=\"left\" class=\"bgEven\">客户姓名</td>\r\n <td class=\"bgOOD\" style=\"background:#ffffff\">\r\n <span id=\"sp_cusName\"></span>\r\n </td>\r\n <td style=\"width:100px\" align=\"left\" class=\"bgEven\">店铺</td>\r\n <td class=\"bgOOD\" style=\"background:#ffffff\">\r\n <span id=\"sp_Company\"></span>\r\n </td>\r\n </tr>\r\n\r\n <tr>\r\n <td style=\"width:100px\" align=\"left\" class=\"bgEven\">客户号码</td>\r\n <td class=\"bgOOD\" style=\"background:#ffffff\">\r\n <span id=\"sp_Phone\"></span>\r\n </td>\r\n <td style=\"width:100px\" align=\"left\" class=\"bgEven\">号码归属地</td>\r\n <td class=\"bgOOD\" style=\"background:#ffffff\">\r\n <span id=\"sp_phoneArea\"></span>\r\n </td>\r\n </tr>\r\n\r\n <tr>\r\n\r\n <td style=\"width:100px\" align=\"left\" class=\"bgEven\">意向车型</td>\r\n <td class=\"bgOOD\" style=\"background: #ffffff\">\r\n <span id=\"sp_attendCar\"></span>\r\n </td>\r\n <td class=\"bgEven\">意向等级</td>\r\n <td class=\"bgOOD\" style=\"background:#ffffff\">\r\n <span id=\"sp_attendLevel\"></span>\r\n </td>\r\n </tr>\r\n\r\n <tr>\r\n\r\n <td class=\"bgEven\">负责销售</td>\r\n <td class=\"bgOOD\" style=\"background:#ffffff\">\r\n <span id=\"sp_SaleName\"></span>\r\n </td>\r\n </tr>\r\n </table>\r\n <!--end 展示信息-->\r\n <!--销售代表列表-->\r\n <div id=\"div_DealerSales\">\r\n <table border=\"0\">\r\n <tr>\r\n <td style=\"width:200px\">\r\n\r\n <select class=\"sel_orderSales\" id=\"sel_orderSales\" style=\"width:200px\">\r\n <option phone=\"0\" value=\"-1\">请选择要分配的人员</option>\r\n </td>\r\n <td style=\"font-size:12px;color:red;\">\r\n <span id=\"sp_warn\">分配后,此客户以后的新线索将直接转给该人员</span>\r\n </td>\r\n </tr>\r\n </table>\r\n </div>\r\n <!--销售代表列表-->\r\n\r\n </div>\r\n </div>\r\n <!-- end 弹框html代码 -->\r\n </div>\r\n <div class=\"m-friendly p15\">\r\n <p>说明:</p>\r\n <p>上牌地区:订单中填写的地区,或400客户号码所在地。</p>\r\n <p>意向车型:订单填写的意向车型,400线索为空。</p>\r\n <p>线索获得时间:私有订单、公共订单、公共400的分配时间,私有400的创建时间。默认显示最近3个月。按线索获得时间筛选,未分配的订单在列表中出现可分配,导出表中不出现。</p>\r\n <p>线索状态:订单的分配、跟进状态,400的接听状态。</p>\r\n <p>线索类型:订单、400的区分,私有、公共的区分。</p>\r\n </div>\r\n</div>\r\n\r\n<div id=\"time\" style=\"display:none;\">\r\n <div class=\"m-memberlist\">\r\n <h4 class=\"memberlist-tit\">线索获得时间说明:</h4>\r\n <div class=\"memberlist-con\">\r\n <p>私有订单:分配算获得,按分配时间显示。如果不分配,标准版超过15小时会丢失,豪华版超过48小时会丢失。</p>\r\n <p>公共订单、公共400:分配算获得,按分配时间显示。</p>\r\n <p>私有400:来电算获得,按来电时间显示。</p>\r\n </div>\r\n </div>\r\n</div>\r\n\r\n<link href=\"//x.autoimg.cn/dealer/ics/20170725A/Content/datetextbox.css\" rel=\"stylesheet\" />\r\n\r\n\r\n</div>\r\n\r\n<input id=\"currentapp\" name=\"currentapp\" type=\"hidden\" value=\"/Dms/Order/Search\" />\r\n<input id=\"currenturl\" name=\"currenturl\" type=\"hidden\" value=\"Order/Search\" />\r\n\r\n<div class=\"ics_copyright\">copyright &copy; 2004-2017 www.autohome.com.cn All Rights Reserved. 汽车之家 版权所有</div>\r\n <script type=\"text/javascript\" src='//x.autoimg.cn/dealer/ics/20170725A/Scripts/jquery-1.10.2.min.js'></script>\r\n <script type=\"text/javascript\" src='//x.autoimg.cn/dealer/ics/20170725A/Scripts/bootstrap.min.js'></script>\r\n <script type=\"text/javascript\" src='//x.autoimg.cn/dealer/ics/20170725A/Scripts/respond.min.js'></script>\r\n <script type=\"text/javascript\" src='//x.autoimg.cn/dealer/ics/20170725A/Scripts/jquery.validate.min.js'></script>\r\n <script type=\"text/javascript\" src='//x.autoimg.cn/dealer/ics/20170725A/Scripts/jquery.validate.unobtrusive.min.js'></script>\r\n <script type=\"text/javascript\" src='//x.autoimg.cn/dealer/ics/20170725A/Scripts/jquery.artDialog.js'></script>\r\n <script type=\"text/javascript\" src='//x.autoimg.cn/dealer/ics/20170725A/Scripts/jquery.cookie.js'></script>\r\n <script type=\"text/javascript\" src='//x.autoimg.cn/dealer/ics/20170725A/Scripts/knockout.js'></script>\r\n <script type=\"text/javascript\" src='//x.autoimg.cn/dealer/ics/20170725A/Scripts/knockout.mapping.js'></script>\r\n <script type=\"text/javascript\" src='//x.autoimg.cn/dealer/ics/20170725A/Scripts/knockout.loader.js'></script>\r\n <script type=\"text/javascript\" src='//x.autoimg.cn/dealer/ics/20170725A/Scripts/common.js'></script>\r\n\r\n <script type=\"text/javascript\" src=\"//x.autoimg.cn/dealer/ics/20170725A/Scripts/json2.js\"></script>\r\n <script src=\"//x.autoimg.cn/dealer/ics/20170725A/Scripts/newics/headCommon.js\"></script>\r\n <script src=\"https://x.autoimg.cn/bi/ahas_head.20160510.min.js\"></script>\r\n <script src=\"https://x.autoimg.cn/bi/ics/ahas_body.20170210.min.js\"></script>\r\n \r\n \r\n\r\n<script src=\"//x.autoimg.cn/dealer/ics/20170725A/Scripts/DMS/dms-common.js\"></script>\r\n<script src=\"//x.autoimg.cn/dealer/ics/20170725A/Scripts/DMS/dms-order-search.js?V=20161230\"></script>\r\n<script src=\"//x.autoimg.cn/dealer/ics/20170725A/Scripts/DMS/jqExtend.js\"></script>\r\n\r\n<script src='//x.autoimg.cn/dealer/ics/20170725A/Scripts/datetextbox.js' type=\"text/javascript\"></script>\r\n<script src=\"//x.autoimg.cn/dealer/ics/20170725A/Scripts/DMS/dialog.min.js\"></script>\r\n<script src=\"//x.autoimg.cn/dealer/ics/20170725A/Scripts/audiojs/audio.js\"></script>\r\n\r\n <script>\r\n //(function ($) {\r\n var d1 = dialog({\r\n align: 'bottom left',\r\n content: $(\"#time\").html(),\r\n skin: \"m-arttips\",\r\n width: 300,\r\n quickClose: false\r\n });\r\n $(document).on(\"mouseenter\", \".j-wen\", function () {\r\n d1.show(this);\r\n });\r\n $(document).on(\"mouseleave\", \".j-wen\", function () {\r\n d1.close(this);\r\n });\r\n // })(jQuery);\r\n </script>\r\n\r\n\r\n</body>\r\n</html>\r\n"
\ No newline at end of file
try.png

269 KB

try2.png

104 KB

Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment