【发布时间】: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