zoukankan      html  css  js  c++  java
  • js fetch

    返回的对象

    type string
    url string
    redirected boolean
    status number
    ok boolean
    statusText string
    headers object
    body object
    bodyUsed boolean
    clone function
    
    arrayBuffer function
    blob function
    formData function
    json function
    text function
    

    get 和 post

            get() {
              let headers = new Headers();
              headers.append('Content-Type', 'application/json');
    
              let option = {
                method: 'GET',
                headers: headers,
                mode: 'cors',
                cache: 'default'
              };
    
              let request = new Request('/get', option);
              fetch(request).then(res => res.json()).then(res => console.log(res));
            
    
            post() {
              let headers = new Headers();
              headers.append('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
    
              let option = {
                method: 'POST',
                headers: headers,
                mode: 'cors',
                cache: 'default'
              };
    
              let request = new Request('/post', option);
              fetch(request).then(res => res.json()).then(res => console.log(res));
    
            }
    

    rxjs 包装 fetch

    let get$ = rxjs.from(fetch('/get', {
      method: 'GET',
      headers: headers
    }))
    
    get$
      .pipe(rxjs.operators.mergeMap(res => rxjs.from(res.json())))
      .subscribe(console.log)
    

    并发请求

    let get$ = rxjs.from(fetch('/get', {method: 'GET',headers: headers}))
    
    let get1$ = rxjs.from(fetch('/get1', {method: 'GET',headers: headers}))
    
    let get2$ = rxjs.from(fetch('/get2', {method: 'GET',headers: headers}))
    
    rxjs.merge(get$, get1$, get2$)
      .pipe( rxjs.operators.mergeMap(res => rxjs.from(res.json())) )
      .subscribe(console.log)
    

    读取流

    fetch("http://localhost:3000/api/stream")
      .then((r) => r.body)
      .then((body) => body.getReader())
      .then(async (reader) => {
        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          const resString = new TextDecoder("utf-8").decode(value);
          console.assert(JSON.parse(resString).data === 100);
        }
        console.log("done.");
      });
    
      @Get('/stream')
      stream() {
        return of(JSON.stringify({ data: 100 })).pipe(delay(2000));
      }
    

    发送流

    example 1:

    const r$ = new ReadableStream({
      start(c) {
        c.enqueue("hello ");
        setTimeout(() => {
        c.enqueue("world");
          c.close();
        }, 2000);
      },
    });
    
    await fetch("http://localhost:3000/api/stream", {
      method: "POST",
      body: r$.pipeThrough(new TextEncoderStream()),
      allowHTTP1ForStreamingUpload: true,
    });
    

    example 2:

    const { writable, readable } = new TransformStream();
    const w$ = writable.getWriter();
    w$.write("hello ");
    setTimeout(() => {
      w$.write("world");
      w$.close();
    }, 2000);
    
    await fetch("http://localhost:3000/api/stream", {
      method: "POST",
      body: readable.pipeThrough(new TextEncoderStream()),
      allowHTTP1ForStreamingUpload: true,
    });
    
    import * as rawbody from 'raw-body';
    
      @Post('/stream')
      async stream(@Req() req) {
        const raw = await rawbody(req);
        const text = raw.toString('utf-8').trim();
        console.log(text);
        return 'hello';
      }
    

    See also:

  • 相关阅读:
    传感器系列之4.4超声测距传感器
    传感器系列之4.3流量传感器
    传感器系列之4.2气压传感器
    传感器系列之4.12GPS定位传感器
    传感器系列之4.1振动传感实验
    传感器系列之3.4继电器
    传感器系列之3.2直流电机
    Spring切面编程步骤
    SpringMVC中的java.lang.ClassNotFoundException: org.aspectj.weaver.BCException 调试过程记录
    SpringMVC中使用@Value给非String类型注入值
  • 原文地址:https://www.cnblogs.com/ajanuw/p/8279944.html
Copyright © 2011-2022 走看看