代码之家  ›  专栏  ›  技术社区  ›  Sergio

Javascript使用异步加载本地。txt文件

  •  0
  • Sergio  · 技术社区  · 6 年前

    我正在尝试使用异步函数加载。txt文件与我的项目位于同一目录中,但我在控制台中看不到响应(文件的实际内容)。日志

    我错过了什么?

      async function myFunct(file){
         try {
            fetch(file).then(function(res){
               return res;
            }).then(function(resp){
               console.log (resp);
            });
         } catch(e) {
            console.log("The Error: " + e);
         } finally {
    
         }
      }
    
      myFunct('./text.txt');
    

    文本。txt文件包含:

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora vero repudiandae dicta maxime quos temporibus labore exercitationem.
    

    以下是日志:

    Response {type: "basic", url: "http://{project_path}/text.txt", redirected: false, status: 200, ok: true, …}
    body:ReadableStream
    locked:false
    __proto__:Object
    bodyUsed:false
    headers:Headers {}
    ok:true
    redirected:false
    status:200
    statusText:"OK"
    type:"basic"
    url:"{project_path}/text.txt"
    __proto__:Response
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   Daniel A. White    6 年前

    res 是一个 Response 对象如果你想要它的文本,请致电 .text()

        fetch(file).then(function(res){
           return res.text(); // change here
        }).then(function(resp){
           return resp; // your content here
        });