本文整理匯總了TypeScript中isomorphic-fetch.default函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript default函數的具體用法?TypeScript default怎麽用?TypeScript default使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了default函數的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: issueRequest
function issueRequest(baseUrl: string, req: string | Request, init?: RequestInit): Promise<any> {
// Resolve relative URLs
if (baseUrl) {
if (req instanceof Request) {
const reqAsRequest = req as Request;
reqAsRequest.url = url.resolve(baseUrl, reqAsRequest.url);
} else {
req = url.resolve(baseUrl, req as string);
}
} else if (!isBrowser) {
// TODO: Consider only throwing if it's a relative URL, since absolute ones would work fine
throw new Error(`
When running outside the browser (e.g., in Node.js), you must specify a base URL
before invoking domain-task's 'fetch' wrapper.
Example:
import { baseUrl } from 'domain-task/fetch';
baseUrl('http://example.com'); // Relative URLs will be resolved against this
`);
}
// Currently, some part of ASP.NET (perhaps just Kestrel on Mac - unconfirmed) doesn't complete
// its responses if we send 'Connection: close', which is the default. So if no 'Connection' header
// has been specified explicitly, use 'Connection: keep-alive'.
init = init || {};
init.headers = init.headers || {};
if (!init.headers['Connection']) {
init.headers['Connection'] = 'keep-alive';
}
return isomorphicFetch(req, init);
}
示例2: fetch
get<T>(key: string): Promise<T>{
const url = this.getUrlForKey(key);
const promise = this.requestInit ? fetch(url, this.requestInit()) : fetch(url);
return promise.then(r => {
if (r.ok){
return r.json<T>()
}
return Promise.reject("Unable to fetch");
})
}
示例3: fetchWithLogin
async function fetchWithLogin(url: string, options?) {
try {
const token = localStorage.getItem('token');
if (token) {
return await fetch(url, Object.assign({}, options, {headers: Object.assign({}, options && options.headers || {}, {Authorization: `Bearer ${token}`})}));
} else {
return await fetch(url, Object.assign({}, options, isBundle ? {credentials: 'include'} : {}));
}
} catch (e) {
throw new Error(e.message);
}
}
示例4: it
it('should create a root user', async () => {
const userExecutor = kiln.build('user', sqlExtension)
state.rootUser = await userExecutor.create({
firstName: 'Root',
lastName: 'User',
accountId: state.account.id,
role: 'admin',
email: 'root@example.com',
password: 'password12',
})
await sqlExtension.sequelize.query(
`UPDATE example_users SET role = 'root' WHERE id = ${state.rootUser.id}`,
)
Object.assign(state.rootUser, {
role: 'root',
createdAt: state.rootUser.createdAt.toJSON(),
updatedAt: state.rootUser.updatedAt.toJSON(),
})
const login = {grant_type: 'password', username: 'root@example.com', password: 'password12'}
const loginResponse = await fetch(`${state.baseURL}/v1/oauth/token`, {
method: 'POST',
body: JSON.stringify(login),
headers: {'content-type': 'application/json'},
})
const token = (await loginResponse.json()).access_token
state.rootCookie = `token=${token}`
})
示例5: issueRequest
function issueRequest(baseUrl: string, req: string | Request, init?: RequestInit): Promise<any> {
const reqUrl = (req instanceof Request) ? req.url : req;
const isRelativeUrl = reqUrl && !isAbsoluteUrl(reqUrl);
// Resolve relative URLs
if (baseUrl) {
if (req instanceof Request) {
const reqAsRequest = req as Request;
(reqAsRequest as any).url = url.resolve(baseUrl, reqAsRequest.url);
} else {
req = url.resolve(baseUrl, req as string);
}
} else if (isNode) {
// TODO: Consider only throwing if it's a relative URL, since absolute ones would work fine
throw new Error(`
When running outside the browser (e.g., in Node.js), you must specify a base URL
before invoking domain-task's 'fetch' wrapper.
Example:
import { baseUrl } from 'domain-task/fetch';
baseUrl('http://example.com'); // Relative URLs will be resolved against this
`);
}
init = applyHttpsAgentPolicy(init, isRelativeUrl, baseUrl);
return isomorphicFetch(req, init);
}
示例6: it
it('should return only published articles when not connected', mochaAsync(async () => {
const articles = await(await fetch('http://localhost:1337/api/article')).json<IArticle[]>();
chai.expect(articles).to.be.a('array');
chai.expect(articles).to.have.length(2);
chai.expect(articles[0].title).to.equal(article1.title);
chai.expect(articles[1].description).to.equal(article2.description);
}));
示例7: getConfig
export async function getConfig() {
const response = await fetch(`${appUrl}/config`);
const config = await response.json();
backOfficeUrl = config.backOfficeUrl;
appUrl = config.appUrl;
return true;
}
示例8: fetchJson
async function fetchJson(url, args) {
const { headers = {} } = args;
headers['Content-Type'] = 'application/json';
let response;
try {
response = await fetch(url, { ...args, headers });
} catch (networkError) {
// e.g. server unreachable
throw ({
error: `Network error: ${networkError.toString()}`,
});
}
let body;
try {
body = await response.json();
} catch (convertError) {
throw ({
error: `Response was not JSON: ${convertError.toString()}`,
});
}
if (response.ok) {
// HTTP 2xx
return body;
} else {
// HTTP 4xx, 5xx (e.g. malformed JSON request)
throw body;
}
}
示例9: fetch
private queryServer<T>(method:string, path:string, data?:any):Promise<T> {
let fullpath = this.constructPath(path);
let headers = new Headers();
if (this._config.token) {
headers.set("Authorization", this._config.token);
}
if (data) {
headers.set("Content-Type", "application/json");
}
var requestConfig:RequestInit = {
method: method,
mode: "cors",
headers: headers
};
if (data) {
requestConfig.body = JSON.stringify(data);
}
return fetch(fullpath, requestConfig).then(response => {
if (!response.ok) {
if (response.status == 401 || response.status == 403) {
throw new AuthenticationError();
}
throw new StatusError(response.status, response.statusText);
}
return response.json<T>();
});
}
示例10: initPostToCategory
function initPostToCategory(categorySlug, callback) {
"use strict";
// Fetch post title for each category
fetch(`https://public-api.wordpress.com/rest/v1.1/sites/sscodex.wordpress.com/posts/?category=${categorySlug}&order=ASC&fields=ID,title,categories,slug&number=100`)
.then((response) => response.json())
.then((json) => {
const {posts = []} = json;
if (!posts.length) {
return;
}
const filteredPost = posts.filter((post, key) => {
const {categories = []} = post;
let contained = false;
Object.keys(categories).forEach(function(key) {
if (categories[key].slug === categorySlug) {
contained = true;
}
});
if (contained) {
return true;
} else {
return false;
}
});
callback(filteredPost);
});
}