本文整理汇总了TypeScript中http.request函数的典型用法代码示例。如果您正苦于以下问题:TypeScript request函数的具体用法?TypeScript request怎么用?TypeScript request使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了request函数的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1:
(() => {
const tunnelingAgent = tunnel.httpOverHttps({
maxSockets: poolSize, // Defaults to http.Agent.defaultMaxSockets
proxy: { // Proxy settings
host: proxyHost, // Defaults to 'localhost'
port: proxyPort, // Defaults to 443
localAddress, // Local interface if necessary
// Basic authorization for proxy server if necessary
proxyAuth: 'user:password',
// Header fields for proxy server if necessary
headers: {
'User-Agent': 'Node'
},
// CA for proxy server if necessary
ca: [ fs.readFileSync('origin-server-ca.pem')],
// Server name for verification if necessary
servername: 'example.com',
// Client certification for proxy server if necessary
key: fs.readFileSync('origin-server-key.pem'),
cert: fs.readFileSync('origin-server-cert.pem'),
}
});
const req = http.request({
host: 'example.com',
port: 80,
agent: tunnelingAgent
});
})();
示例2: Promise
await new Promise((resolve) => {
const reqData = "name is sparky";
const req = request(
{
socketPath: runtime.metadata.socketPath,
path: "/",
method: "post",
headers: {
"Content-Type": "gibber/ish",
"Content-Length": reqData.length,
},
},
(res) => {
let data = "";
res.on("data", (chunk) => (data += chunk));
res.on("end", () => {
expect(JSON.parse(data).type).to.deep.equal("Buffer");
expect(JSON.parse(data).data.length).to.deep.equal(14);
resolve();
});
}
);
req.write(reqData);
req.end();
});
示例3:
process.on("exit", () => {
http.request({
port: 3001,
path: "/" + name,
method: "DELETE"
}).end();
});
示例4: Headers
ngZome.run(() => {
nodeReq = http.request(reqInfo, (res: http.IncomingMessage) => {
let body = '';
res.on('data', (chunk) => body += chunk);
let status = res.statusCode;
let headers = new Headers(res.headers);
let url = res.url;
res.on('end', () => {
let responseOptions = new ResponseOptions({body, status, headers, url});
let response = new Response(responseOptions);
if (utils.isSuccess(status)) {
ngZome.run(() => {
responseObserver.next(response);
});
ngZome.run(() => {
responseObserver.complete();
});
return;
}
ngZome.run(() => {
responseObserver.error(response);
});
});
});
})
示例5: checkWebsiteIsRunning
function checkWebsiteIsRunning() {
//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
const options: http.RequestOptions = {
host: 'localhost',
port: 4200,
path: '/'
};
const callback = function (response: http.IncomingMessage) {
let content = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
content += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
if (content.indexOf('<title>Croquet Australia Admin Website</title>') < 0) {
console.log('Website content does not include expected title');
console.log(content);
throw new Error('Website is not running');
}
console.log('Website is running');
});
}
http.request(options, callback).end();
}
示例6: sender
public static sender(payload: string, config) {
var headers = {
'Content-Type': 'application/json',
'Content-Length': payload.length,
};
var endpointUrl = config.endpointUrl();
if (endpointUrl && endpointUrl.indexOf("//") === 0) {
// add http protocol if the config did not specify https
endpointUrl = "http:" + endpointUrl;
}
var options = {
host: url.parse(endpointUrl).hostname,
path: url.parse(endpointUrl).pathname,
method: 'POST',
headers: headers
};
var req = http.request(options, (res) => {
res.setEncoding('utf-8');
//returns empty if the data is accepted
var responseString = '';
res.on('data', (data) => {
responseString += data;
});
res.on('end', () => {
});
});
req.write(payload);
req.end();
}
示例7: _getNpmPackageJson
/**
* Get the NPM repository's package.json for a package. This is p
* @param {string} packageName The package name to fetch.
* @param {LoggerApi} logger A logger instance to log debug information.
* @returns {Observable<JsonObject>} An observable that will put the pacakge.json content.
* @private
*/
function _getNpmPackageJson(
packageName: string,
logger: logging.LoggerApi,
): Observable<JsonObject> {
const url = `http://registry.npmjs.org/${packageName.replace(/\//g, '%2F')}`;
logger.debug(`Getting package.json from ${JSON.stringify(packageName)}...`);
let maybeRequest = npmPackageJsonCache.get(url);
if (!maybeRequest) {
const subject = new ReplaySubject<JsonObject>(1);
const request = http.request(url, response => {
let data = '';
response.on('data', chunk => data += chunk);
response.on('end', () => {
try {
const json = JSON.parse(data);
subject.next(json as JsonObject);
subject.complete();
} catch (err) {
subject.error(err);
}
});
response.on('error', err => subject.error(err));
});
request.end();
maybeRequest = subject.asObservable();
npmPackageJsonCache.set(url, maybeRequest);
}
return maybeRequest;
}
示例8: reject
return new Promise<string>((resolve, reject) => {
let unexpectedEnd = () => {
reject({code: 'UNKNOWN', message: 'Request ended unexpectedly'});
};
let req = http.request(
{port: parseInt(port), method: method, path: path, headers: headers}, (res) => {
req.removeListener('end', unexpectedEnd);
if (res.statusCode !== 200) {
reject({code: res.statusCode, message: res.statusMessage});
} else {
let buffer: (string|Buffer)[] = [];
res.on('data', buffer.push.bind(buffer));
res.on('end', () => {
resolve(buffer.join('').replace(/\0/g, ''));
});
}
});
if (timeout) {
req.setTimeout(timeout, () => {
reject({code: 'TIMEOUT', message: 'Request timed out'});
});
}
req.on('error', reject);
req.on('end', unexpectedEnd);
if (hasContent) {
req.write(data as string);
}
req.end();
});
示例9: reject
worker.request = new Promise<PhantomResult>((resolve, reject) => {
const hmac = crypto.createHmac("sha256", worker.key)
.update([worker.counter, 'POST', '/', `localhost:${worker.port}`, 'application/json', payload].join('\n'))
.digest('hex');
http.request({
port: worker.port,
method: 'POST',
auth: worker.counter + ':' + hmac,
headers: {
'Content-Type': 'application/json',
'Content-Length': payload.length,
},
}, (response) => {
let result = '';
response.on('error', (error) => {
reject(error);
});
response.on('data', (data) => {
result += data;
});
response.on('end', () => {
resolve([response, result]);
});
})
.on('error', (error) => {
reject(error);
})
.end(payload);
});