【问题标题】:Javascript fetch API doesnt work when used in EJS fileJavascript fetch API 在 EJS 文件中使用时不起作用
【发布时间】:2021-08-05 23:54:54
【问题描述】:

我正在尝试从(本地托管的)NodeJS 后端的根目录中获取一个名为 files.json 的文件,然后在控制台中将其打印出来。

<script>
fetch("./files.json")
    .then(res => {
        return res.json();
    })
    .then(obj => {
        console.log(obj);
    })
    .catch(err => {
        console.error(err);
    });
</script>

在 index.ejs 文件中使用此代码会在浏览器的控制台中产生以下错误:

GET http://localhost:3000/files.json [HTTP/1.1 404 Not Found 2ms]
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

但是,当我在使用 Visual Studio Code 的 LiveServer 插件在本地托管的 .html 文件中使用完全相同的代码时,我得到了想要的结果:

Object { files: (3) […] }

如果相关,files.json 有以下内容:

{
"files": [
    {
        "name": "testfile1"
    },
    {
        "name": "testfile2"
    },
    {
        "name": "testfile3"
    }
]
}

【问题讨论】:

    标签: javascript node.js express ejs fetch-api


    【解决方案1】:

    您需要将数据输出转换为字符串,即,

     var yourDataStr = JSON.stringify(yourdata) 

    然后验证您的数据:

    JSON.parse(yourDataStr)

    【讨论】:

      【解决方案2】:

      我不确定,但我认为 fetch() 不适用于 NodeJS。它只是浏览器中的本机功能(客户端 Javascript),因此在 NodeJS 中不起作用。要解决此问题,您必须下载 NodeJS 中的库,该库将支持 NodeJS 中的 fetch(),例如 node-fetch

      1. 使用npm install node-fetch安装node-fetch
      2. 然后试试这个例子:
      fetch('') // Here add location for JSON file
                  .then(res => res.json())
                  .then(json => console.log(json));
      

      【讨论】:

        猜你喜欢
        • 2020-10-20
        • 1970-01-01
        • 2020-07-16
        • 1970-01-01
        • 2017-09-29
        • 2013-12-10
        • 1970-01-01
        • 2020-07-15
        • 1970-01-01
        相关资源
        最近更新 更多