• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript querystring.parse函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中querystring.parse函数的典型用法代码示例。如果您正苦于以下问题:TypeScript parse函数的具体用法?TypeScript parse怎么用?TypeScript parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了parse函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: Promise

    const promise: Promise<SUSHInfo> = new Promise((resolve, reject) => {
      const sheetUrlObj = new URL(sheetUrl);

      // Parse URL
      const sheetId = (sheetUrl.match(sheetIdRegExp) || [])[1];
      if (!sheetId) {
        throw new Error('sheetUrl is invalid.');
      }
      // Get gid from hash
      const hashQuery = Object.assign(
        qs.parse(sheetUrlObj.hash.substr(1)),
        qs.parse(sheetUrlObj.search.substr(1))
      );
      if (!('gid' in hashQuery)) {
        throw new Error('sheetUrl must contain gid.');
      }
      // Convert gid to wid
      const sheetKey = Util.convertGidToWid(hashQuery.gid);

      const sheetDataUrl =
        `https://spreadsheets.google.com/feeds/list/${sheetId}/${sheetKey}/public/values?alt=json`;

      // Fetch Google Spreadsheet
      const xhr = new XMLHttpRequest();
      xhr.open('GET', sheetDataUrl, true);
      xhr.addEventListener('load', () => resolve(xhr));
      xhr.addEventListener('error', (ev) => reject(ev.error));
      xhr.send();
    })
开发者ID:3846masa,项目名称:SUSH,代码行数:29,代码来源:index.ts


示例2: getAddressDetails

  /**
   * Process address into address and memo id
   *
   * @param address {String} the address
   * @returns {Object} object containing address and memo id
   */
  getAddressDetails(address) {
    const destinationDetails = url.parse(address);
    const queryDetails = querystring.parse(destinationDetails.query);
    const destinationAddress = destinationDetails.pathname;
    if (!stellar.StrKey.isValidEd25519PublicKey(destinationAddress)) {
      throw new Error(`invalid address: ${address}`);
    }
    // address doesn't have a memo id
    if (destinationDetails.pathname === address) {
      return {
        address: address,
        memoId: null
      };
    }

    if (!queryDetails.memoId) {
      // if there are more properties, the query details need to contain the memo id property
      throw new Error(`invalid address: ${address}`);
    }

    try {
      new BigNumber(queryDetails.memoId);
    } catch (e) {
      throw new Error(`invalid address: ${address}`);
    }

    if (!this.isValidMemoId(queryDetails.memoId)) {
      throw new Error(`invalid address: ${address}`);
    }

    return {
      address: destinationAddress,
      memoId: queryDetails.memoId
    };
  }
开发者ID:BitGo,项目名称:BitGoJS,代码行数:41,代码来源:xlm.ts


示例3: ParseTorrent

const tabUpdated = (tabId: number, url: string, state: TorrentsState) => {
  const { torrentStateMap, torrentObjMap } = state
  const origTorrentState: TorrentState = torrentStateMap[tabId]
  const origInfoHash = origTorrentState ? origTorrentState.infoHash : undefined
  let newTorrentState: TorrentState | undefined
  let newInfoHash: string | undefined

  // create new torrent state
  const parsedURL = new window.URL(url)
  const torrentId = parsedURL.href
  if (parsedURL.protocol === 'magnet:') { // parse torrent
    try {
      const { name, infoHash, ix } = ParseTorrent(torrentId)
      newInfoHash = infoHash
      newTorrentState = { tabId, torrentId, name, infoHash, ix }
    } catch (error) {
      newTorrentState = { tabId, torrentId, errorMsg: error.message }
    }
  } else if (parsedURL.protocol === 'https:' || parsedURL.protocol === 'http:') {
    const name = parsedURL.pathname.substr(parsedURL.pathname.lastIndexOf('/') + 1)
    // for .torrent case, ix (index of file) for selecting a specific file in
    // the file list is given in url like #ix=5
    let ix: number | undefined = Number(parse(parsedURL.hash.slice(1)).ix)
    ix = Number.isNaN(ix) ? undefined : ix

    // Use an existing infoHash if it's the same torrentId
    const torrentUrl = parsedURL.origin + parsedURL.pathname
    const key = Object.keys(torrentStateMap).find(
      key => torrentStateMap[key].infoHash &&
        torrentStateMap[key].torrentId === torrentUrl)
    newInfoHash = key
      ? torrentStateMap[key].infoHash
      : undefined

    newTorrentState = { tabId, torrentId, name, ix, infoHash: newInfoHash }
  }

  // delete old torrent state
  delete torrentStateMap[tabId]

  // unsubscribe old torrent if not the same
  const isSameTorrent = newInfoHash && origInfoHash === newInfoHash
  if (origInfoHash && torrentObjMap[origInfoHash] && !isSameTorrent) {
    torrentObjMap[origInfoHash].tabClients.delete(tabId)
    if (!torrentObjMap[origInfoHash].tabClients.size) {
      delete torrentObjMap[origInfoHash]
      delTorrent(origInfoHash)
    }
  }

  // save new torrent state and subscribe directly if torrent already existed
  if (newTorrentState) {
    torrentStateMap[tabId] = newTorrentState
    if (newInfoHash && torrentObjMap[newInfoHash]) {
      torrentObjMap[newInfoHash].tabClients.add(tabId)
    }
  }

  return { ...state, torrentStateMap, torrentObjMap }
}
开发者ID:Snuupy,项目名称:brave-core,代码行数:60,代码来源:webtorrent_reducer.ts


示例4: http_assemble_json

function http_assemble_json(bodyParts, cb) {
  let body = Buffer.concat(bodyParts).toString()
  if (body.length > 0) {
    try {
      let data = JSON.parse(body)
      cb(data)
    } catch (e) {
      if (e instanceof SyntaxError) {
        let qbody = querystring.parse(body)
        if(qbody) {
	  cb(qbody)
        } else {
          console.log('payload not understood', JSON.stringify(body.substr(0, 280)))
          cb()
        }
      } else {
        console.log('aborting connection.', e.name)
        cb()
      }
    }
  } else {
    console.log('empty body. closed.')
    cb()
  }
}
开发者ID:icecondor,项目名称:api,代码行数:25,代码来源:rest.ts


示例5: parseResponse

/**
 * Parse the response automatically.
 */
function parseResponse (response: Response) {
  const body = response.body

  if (typeof body !== 'string') {
    return
  }

  if (body === '') {
    response.body = null

    return
  }

  const type = response.type()

  try {
    if (JSON_MIME_REGEXP.test(type)) {
      response.body = body === '' ? null : JSON.parse(body)
    } else if (QUERY_MIME_REGEXP.test(type)) {
      response.body = parseQuery(body)
    }
  } catch (err) {
    return Promise.reject(response.error('Unable to parse response body: ' + err.message, 'EPARSE', err))
  }
}
开发者ID:garethhunt,项目名称:popsicle,代码行数:28,代码来源:common.ts


示例6: setTimeout

    echoServer.use(function(req: IncomingMessage, res: ServerResponse) {
        let urlParts = req.url.split("?");

        let returnResponse = () => {
            res.setHeader('Content-Type', 'text/plain');
            res.writeHead(200);
            req.pipe(res);
        };

        if (urlParts.length > 1) {
            const parameters = querystring.parse(urlParts[1]);

            if (parameters.d) {
                res.setHeader('d', parameters.d);
            }
        
            if (parameters.t) {
                res.setHeader('t', parameters.t);
                setTimeout(returnResponse, parameters.t)
            }
            else {
                returnResponse();
            }
            return;
        }

        returnResponse();

    });
开发者ID:roberthardy,项目名称:rp,代码行数:29,代码来源:echoServer.ts


示例7: reject

                (err, res, body) => {
                    if (err) {
                        console.log('POST code error: ' + err.message);
                        reject(err);
                        return;
                    }

                    if (res.statusCode !== 200) {
                        console.log('POST code error: ' + res.statusCode);
                        reject(new Error('Invalid response: ' + res.statusCode));
                        return;
                    }

                    const parsed = querystring.parse(body);
                    if (!parsed.access_token) {
                        console.log('Body parsing error: ' + body);
                        reject(new Error('Invalid body: ' + body));
                    }

                    console.log('Login: Success!');

                    fs.writeFile(this.tokens_path, JSON.stringify({github: parsed.access_token}), {encoding: 'utf8'});

                    resolve(parsed.access_token);
                }
开发者ID:kdallafior,项目名称:Trendy,代码行数:25,代码来源:authentication.ts


示例8: constructor

  constructor(tab: string, instanceIn: TabInstance) {
    this.tab = tab;
    let instance = instanceIn || eo;

    this._instance = instance;
    this._page = currentPage(instance) || eo;

    const { resource, url } = this._page;
    if (resource) {
      const slashIndex = resource.indexOf("/");
      if (slashIndex > 0) {
        this.prefix = resource.substring(0, slashIndex);
        this.suffix = resource.substring(slashIndex + 1);
      } else {
        this.prefix = resource;
      }
    }

    if (url) {
      try {
        const parsed = nodeURL.parse(url);
        this._protocol = parsed.protocol;
        this._hostname = parsed.hostname;
        this._pathname = parsed.pathname;
        this._query = querystring.parse(parsed.query);
        if (parsed.pathname) {
          this._pathElements = parsed.pathname.replace(/^\//, "").split("/");
        }
      } catch (e) {
        // TODO: figure this out
        console.log(`Could not parse url: `, e);
      }
    }
  }
开发者ID:itchio,项目名称:itch,代码行数:34,代码来源:space.ts


示例9: _parseQuery

    /**
     * Parses the template query string
     * @param text The query string to parse
     * @hidden
     */
    private _parseQuery(text: string): void {

        var query = parseQueryString(text);
        this._queryParams = new Map();

        var seen = new Set<string>();

        for(let name in query) {
            if(query[name] !== undefined) {
                var value = query[name];

                var error: string;
                if(!value) {
                    error = "Missing value";
                }
                else if(value.length < 3 || value[0] != "{" || value[value.length-1] != "}") {
                    error = "Value must be a parameter name in the format '{name}'";
                }
                else {
                    var param = value.substring(1, value.length - 1);

                    if ((this._pathParams && this._pathParams.indexOf(param) != -1) || seen.has(param)) {
                        error = `Duplicate parameter name '${param}'`;
                    }
                }
                if(error) {
                    throw new Error(`Invalid query '${name}': ${error}.`);
                }

                // save the map between the query param and the operation param, trimming off the leading colon
                this._queryParams.set(name, param);
                seen.add(param);
            }
        }
    }
开发者ID:artifacthealth,项目名称:service-model,代码行数:40,代码来源:urlTemplate.ts


示例10: navigate

export function navigate(url: string) {
    try {
        const parsed = URL.parse(url);
        if (parsed.protocol === "emulator:") {
            const params = QueryString.parse(parsed.query);
            if (parsed.host === 'inspect') {
                navigateInspectUrl(params);
            } else if (parsed.host === 'appsettings') {
                navigateAppSettingsUrl(params);
            } else if (parsed.host === 'botcreds') {
                navigateBotCredsUrl(params);
            } else if (parsed.host === 'command') {
                navigateCommandUrl(params);
            }
        } else if (parsed.protocol.startsWith(PaymentEncoder.PaymentEmulatorUrlProtocol)) {
            navigatePaymentUrl(parsed.path);
        } else if (parsed.protocol.startsWith(OAuthClientEncoder.OAuthEmulatorUrlProtocol)) {
            navigateEmulatedOAuthUrl(url.substring(8));
        } else if (parsed.protocol.startsWith(OAuthLinkEncoder.OAuthUrlProtocol)) {
            navigateOAuthUrl(url.substring(12));
        } else if (parsed.protocol.startsWith('file:')) {
            // ignore
        } else if (parsed.protocol.startsWith('javascript:')) {
            // ignore
        } else {
            shell.openExternal(url, { activate: true });
        }
    } catch (e) {
        log.error(e.message);
    }
}
开发者ID:kpreeti096,项目名称:BotFramework-Emulator,代码行数:31,代码来源:hyperlinkHandler.ts


示例11: handleApiAsync

function handleApiAsync(req: http.IncomingMessage, res: http.ServerResponse, elts: string[]): Promise<any> {
    let opts: U.Map<string> = querystring.parse(url.parse(req.url).query)
    let innerPath = elts.slice(2).join("/").replace(/^\//, "")
    let filename = path.resolve(path.join(fileDir, innerPath))
    let meth = req.method.toUpperCase()
    let cmd = meth + " " + elts[1]

    let readJsonAsync = () =>
        nodeutil.readResAsync(req)
            .then(buf => JSON.parse(buf.toString("utf8")))

    if (cmd == "GET list")
        return returnDirAsync(innerPath, 3)
            .then<ks.FsPkgs>(lst => {
                return {
                    pkgs: lst
                }
            })
    else if (cmd == "GET stat")
        return statOptAsync(filename)
            .then(st => {
                if (!st) return {}
                else return {
                    mtime: st.mtime.getTime()
                }
            })
    else if (cmd == "GET pkg")
        return readPkgAsync(innerPath, true)
    else if (cmd == "POST pkg")
        return readJsonAsync()
            .then(d => writePkgAsync(innerPath, d))
    else throw throwError(400)
}
开发者ID:YanLinAung,项目名称:kindscript,代码行数:33,代码来源:server.ts


示例12: verifyUrl

    verifyUrl(req: Request, addressReader?: Types.AddressReader): Types.VerifyResult {
        const url = req.protocol+'://'+req.get('host')+req.url;

        if( url.length < 33  ||  !this.verifyString( url.substring(0, url.length-32), url.substr(-32) ) ) {
            return Types.VerifyResult.blackholed;
        }

        // get signed data
        let lastAmpPos = url.lastIndexOf('&signed=');
        if(lastAmpPos == -1) {
            lastAmpPos = url.lastIndexOf('?signed=');
        }
        if(lastAmpPos == -1) {
            return Types.VerifyResult.blackholed;
        }
        const data = querystring.parse( url.substring(lastAmpPos+8, url.length-33), ';', ':');
        req.url = url.substr(0, lastAmpPos);

        // check additional conditions
        if(data.a  &&  addressReader  &&  data.a != addressReader(req)) {
            return Types.VerifyResult.blackholed;
        }
        if(data.m  &&  data.m.indexOf(req.method) == -1) {
            return Types.VerifyResult.blackholed;
        }
        if(data.e  &&  data.e < Math.ceil(+new Date()/1000)) {
            return Types.VerifyResult.expired;
        }
        return Types.VerifyResult.ok;
    }
开发者ID:smbwain,项目名称:signed,代码行数:30,代码来源:index.ts


示例13:

        responses.forEach(response => {
            let urlParts = response.request.path.split("?");
            const parameters = querystring.parse(urlParts[1]);

            if (parameters.d != response.data) {
                throw `Expected '${parameters.d}' but received '${response.data}'`;
            }
        });
开发者ID:roberthardy,项目名称:rp,代码行数:8,代码来源:traceTest.ts


示例14: doAsync

 doAsync(async () => {
   const queryParams = querystring.parse(parsedURL.query);
   const gameId = parseInt(queryParams["game_id"] as string, 10);
   const uploadId = parseInt(queryParams["upload_id"] as string, 10);
   logger.info(`Should queue install because of URL: ${url}`);
   const { game } = await mcall(messages.FetchGame, { gameId });
   await queueInstall(store, game, uploadId);
 });
开发者ID:itchio,项目名称:itch,代码行数:8,代码来源:url.ts


示例15: function

    http.createServer(function (req, resultServer) {
        if (req.url.match(/^\/login/)) {
            var param = qs.parse(req.url.split('?')[1]);

            remote.auth(param.user, param.pass, function (error, resultAuth) {
                resultServer.end(error ? error : resultAuth);
            });
        }
    }).listen(process.argv[2]);
开发者ID:acrobat888,项目名称:NodeJS,代码行数:9,代码来源:web.ts


示例16:

rpn.post({ url, oauth }, (e, r, body) => {
  // Ideally, you would take the body in the response
  // and construct a URL that a user clicks on (like a sign in button).
  // The verifier is only available in the response after a user has
  // verified with twitter that they are authorizing your app.

  // step 2
  let req_data = qs.parse(body);
  let uri = 'https://api.twitter.com/oauth/authenticate'
    + '?' + qs.stringify({ oauth_token: req_data.oauth_token });
  // redirect the user to the authorize uri

  // step 3
  // after the user is redirected back to your server
  let auth_data: any = qs.parse(body);
  let oauth = {
    consumer_key: CONSUMER_KEY,
    consumer_secret: CONSUMER_SECRET,
    token: auth_data.oauth_token,
    token_secret: req_data.oauth_token_secret,
    verifier: auth_data.oauth_verifier,
  };
  url = 'https://api.twitter.com/oauth/access_token';

  rpn.post({ url, oauth }, (e, r, body) => {
    // ready to make signed requests on behalf of the user
    let perm_data: any = qs.parse(body);
    let oauth = {
      consumer_key: CONSUMER_KEY,
      consumer_secret: CONSUMER_SECRET,
      token: perm_data.oauth_token,
      token_secret: perm_data.oauth_token_secret,
    };

    url = 'https://api.twitter.com/1.1/users/show.json';
    let query = {
      screen_name: perm_data.screen_name,
      user_id: perm_data.user_id
    };
    rpn.get({ url, oauth, qs: query, json: true }, (e, r, user) => {
      console.log(user);
    });
  });
});
开发者ID:Crevil,项目名称:DefinitelyTyped,代码行数:44,代码来源:request-promise-native-tests.ts


示例17: function

var getTokenFromUrl = function() : AuthProps {
    let { access_token, expires_in} = qs.parse(window.location.hash.substr(1));
    return access_token && expires_in 
        ? { 
            profile: null, 
            access_token: (access_token as string), 
            expires: addSeconds(new Date(), parseInt(expires_in as string,10) - 120) 
        } 
        : null;
}
开发者ID:DroopyTersen,项目名称:droopy-static,代码行数:10,代码来源:azureADAuth.ts


示例18: generateToken

    .reply((uri: string, requestBody: string) => {

      const body = querystring.parse(requestBody);

      const scope = body.scope ? body.scope.toString().split(' ') : undefined;

      const newToken = generateToken(scope);
      _tokens.push(newToken);

      return [HttpStatus.OK, newToken];
    });
开发者ID:zalando-incubator,项目名称:lib-oauth-tooling,代码行数:11,代码来源:index.ts


示例19: toObj

export function toObj(str?:string) : any {
	//if no string is passed use window.location.search
	if (str === undefined && window && window.location && window.location.search) {
		str = window.location.search;
	}
	if (!str) return {};
	//trim off the leading '?' if its there
	if (str[0] === "?") str = str.substr(1);

	return qs.parse(str);    
}
开发者ID:DroopyTersen,项目名称:spscript,代码行数:11,代码来源:queryString.ts


示例20: constructor

    constructor(data:string) {
    	var params:any = {};
		try {
			if (isString(data) && data.slice(0, 1) === "{") {
				params = JSON.parse(data);
			} else if (isString(data)) {
				params = qs.parse(data);
			}
		} catch (error) {
		}
        super(params);
    }
开发者ID:rodzewich,项目名称:playground,代码行数:12,代码来源:queryHelper.ts



注:本文中的querystring.parse函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript querystring.stringify函数代码示例发布时间:2022-05-25
下一篇:
TypeScript querystring.escape函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap