本文整理汇总了TypeScript中node-fetch.default方法的典型用法代码示例。如果您正苦于以下问题:TypeScript node-fetch.default方法的具体用法?TypeScript node-fetch.default怎么用?TypeScript node-fetch.default使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类node-fetch
的用法示例。
在下文中一共展示了node-fetch.default方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: request
export default function request({
token, name
}: any): Promise<StampRally> {
const urlObj = url.parse('https://api.rallyapp.jp/stamp_rallies/');
urlObj.query = { view_type: 'admin' };
return fetch(
url.format(urlObj),
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Token token="' + token + '"',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name,
display_name: 'stamprally',
tagline: 'tagline',
description: 'description',
display: false,
open: false,
display_start_datetime: '2016-01-01T00:00:00Z',
display_end_datetime: '2016-12-31T00:00:00Z',
start_datetime: '2016-01-01T00:00:00Z',
end_datetime: '2016-12-31T00:00:00Z'
})
}
)
.then((response: any) => response.json())
.then((stampRally: StampRally) => stampRally);
}
示例2: test_fetchUrlWithOptions
function test_fetchUrlWithOptions() {
var headers = new _fetch.Headers();
headers.append("Content-Type", "application/json");
var requestOptions: _fetch.RequestInit = {
method: "POST",
headers: headers,
mode: 'same-origin',
credentials: 'omit',
cache: 'default',
redirect: 'manual'
};
handlePromise(fetch("http://www.andlabs.net/html5/uCOR.php", requestOptions));
}
示例3: request
export default function request({ token, stampRallyId }: any): Promise<Spot[]> {
const urlObj = url.parse(
'https://api.rallyapp.jp/stamp_rallies/' + stampRallyId + '/spots'
);
urlObj.query = { view_type: 'admin' };
return fetch(
url.format(urlObj),
{
method: 'GET',
headers: {
'Accept': 'application/json',
'Authorization': 'Token token="' + token + '"',
'Content-Type': 'application/json'
}
}
)
.then((response: any) => response.json())
.then(({ spots }) => spots);
}
示例4: it
it('should support fields', async () => {
// the custom fields not already be in the base fields
expect(User.fields.custom.fields).to.be.undefined;
let result = await fetch(urlPrefix + '/api/user/custom', {
method: 'put',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ organization: 1 })
});
let json = await result.json();
expect(_.keys(json.fields)).to.eql(['custom', 'acmeY']);
// should also merge nested fields
expect(_.keys(json.fields.custom.fields)).to.eql(['nested1', 'nested2']);
// it should NOT modify the base fields
expect(User.fields.custom.fields).to.be.undefined;
expect(json.fields.custom.fields.nested1.label).to.eql('Nested 1');
result = await fetch(urlPrefix + '/api/organization/custom', {
method: 'put',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ foo: 1 })
});
json = await result.json();
expect(_.keys(json.fields)).to.eql([]);
});
示例5: downloadPackage
export function downloadPackage(type: PackageType, metadata: PackageMetadata): Promise<string> {
let { version, dist: { platform, format, url } } = metadata;
let packageBaseName = `${type}-${version}-${platform}`
let packageName = `${packageBaseName}.${format}`;
let metadataFileName = `${packageBaseName}.json`;
let packagePath = Path.join(config.downloadsPath, packageName);
let metadataFilePath = Path.join(config.downloadsPath, metadataFileName);
if (FS.existsSync(packagePath) && FS.existsSync(metadataFilePath)) {
return Promise.resolve(packagePath);
}
let tmpPackagePath = Tmp.tmpNameSync();
return Promise
.resolve(fetch(url))
.then(res => {
let resStream = res.body;
let writeStream = FS.createWriteStream(tmpPackagePath);
resStream.pipe(writeStream);
return Promise.for(writeStream, 'close', [resStream]);
})
.then(() => {
FS.copySync(tmpPackagePath, packagePath);
let metadataJSON = JSON.stringify(metadata, undefined, 4);
FS.writeFileSync(metadataFilePath, metadataJSON);
return packagePath;
});
}
示例6: getZfxFormContent
public static async getZfxFormContent(transaction_id: string, vendor_form_id: string, zfx_form_version: string, context_id: string) {
const headers = {
'Content-Type': 'application/json',
'X-Auth-ContextId': context_id,
'X-Auth-SharedKey': zipFormSharedKey
};
// const response = await fetch(`${zipFormURL}/api/transactions/${transaction_id}/documents/${vendor_form_id}/${zfx_form_version}`, {
// method: 'GET',
// headers
// });
const response = await fetch(`https://h5.zipformonline.com/api/transactions/0f1ee286-e455-4e3b-8003-702aa25b925a/documents/B3466E24-24E0-4355-95FD-EB84E7AEBDE5/812.0`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-Auth-ContextId': '9b4b8ab6-2504-40b2-be22-afbf7f12ec54',
'X-Auth-SharedKey': '36441E42-40E8-4A63-AC52-269765422884'
}
});
const data = await response.buffer();
if (data) {
// const base64data = new Buffer(data, 'utf-8');
const fileupload = await this.uploadFileToS3(data, 'khanh.test');
console.log(fileupload);
// console.log(data.body);
return data;
} else {
const errMsg = `Error getting content for =${vendor_form_id}`;
console.log(errMsg, data);
throw new Error(errMsg);
}
}
示例7: test_fetchUrlWithHeadersObject
function test_fetchUrlWithHeadersObject() {
var requestOptions: _fetch.RequestInit = {
method: "POST",
headers: {
'Content-Type': 'application/json'
}
};
handlePromise(fetch("http://www.andlabs.net/html5/uCOR.php", requestOptions));
}
示例8: deployModel
async function deployModel(service, stage, datamodel) {
await fetch(`http://localhost:4466/management`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `mutation {
addProject(input: {
name: "${service}"
stage: "${stage}"
}) {
clientMutationId
}
}`,
}),
})
const variables = {
input: {
name: service,
stage,
types: datamodel,
},
}
await fetch(`http://localhost:4466/management`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `mutation ($input: DeployInput!) {
deploy(input: $input) {
clientMutationId
}
}`,
variables,
}),
})
}
示例9: getPackageMetadata
export function getPackageMetadata(range = '*'): Promise<PackageMetadata> {
let versionsUrl = `${config.registry}/sdks.json`;
return Promise
.resolve(fetch(versionsUrl))
.then(res => res.json<VersionsData>())
.then(data => {
let { tags, packages } = data;
let versions = Object.keys(packages);
let version = match(range, versions, tags);
if (!version) {
throw new ExpectedError(`No matching version found for "${range}"`);
}
let { dists } = packages[version];
let priorPlatformName = `${process.platform}-${process.arch}`
let possiblePlatformNames = [
priorPlatformName,
process.platform
];
let dist: Distribution;
let platformName: string;
for (let platformName of possiblePlatformNames) {
if (hasOwnProperty.call(dists, platformName)) {
let rawDist = dists[platformName];
dist = {
platform: platformName,
format: rawDist.format,
url: rawDist.url,
strip: rawDist.strip
};
break;
}
}
if (!dist) {
throw new ExpectedError(`No matching distribution package found for platform "${priorPlatformName}"`);
}
return {
version,
dist
};
});
}
示例10: if
private async createRequest<T>(method: "GET" | "POST" | "PUT" | "DELETE", path: string, payload?: Object)
{
method = method.toUpperCase() as any;
const url = new uri(`https://api.sendwithus.com/api/v1/${path}`);
const options = {
headers: this.buildDefaultHeaders(),
method: method,
body: undefined as string,
};
if ((method === "GET" || method === "DELETE") && payload)
{
for (const prop in payload)
{
const value = payload[prop];
//qs array values should be joined by a comma, e.g. fields=field1,field2,field3
url.addQueryParam(prop, Array.isArray(value) ? value.join(",") : value);
}
}
else if (payload)
{
options.body = JSON.stringify(payload);
options.headers.append("Content-Type", "application/json");
}
//Fetch will only throw an exception when there is a network-related error, not when the service returns a non-200 response.
const result = await fetch(url.toString(), options);
let json = await result.text() as any;
try
{
json = JSON.parse(json);
}
catch (e)
{
//Set ok to false to throw an error with the body's text.
result.ok = false;
}
if (!result.ok)
{
throw new Error(result.statusText, result.status);
}
return json as T;
}