在 Vue JavaScript 中使用 Fetch API 时出错

Error in using Fetch API in Vue JavaScript

我使用下面的代码使用fetch读取文件:

fetch('rest.txt', {mode: 'no-cors'})
      .then(response => response.text())
      .then(data=> console.log(data));

在浏览器控制台中,我得到以下响应而不是文件文本。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="./static/favicon.ico"/>
    <title>TRAINSET</title>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-91042619-2"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'UA-91042619-2');
    </script>
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  <script type="text/javascript" src="/app.js"></script></body>
</html>
<style>
html, body {
  max-width: 100% !important;
  overflow-x: hidden !important;
}
</style>

我昨天也试过同样的方法,效果很好,但今天却不行。

有人可以帮我解决这个问题吗?

奇怪,我已经直接复制了那个代码和 运行 with http-server

  fetch('/rest.txt', {mode: 'no-cors'})
      .then(response => response.text())
      .then(data=> console.log(data)); 

有效

您能否显示使用该代码的所有上下文?

只需添加 var customData = require('./rest.txt'); 在开始。 它为我解决了问题。 如果没有这个,如果它在服务器上 运行ning,则 fetch 将不会 运行。 如果没有服务器 运行ning,fetch 将在没有它的情况下工作。