[英]Javascript fetch API doesnt work when used in EJS file
我正在尝试从(本地托管的)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"
}
]
}
您需要将数据 output 转换为字符串,即
var yourDataStr = JSON.stringify(yourdata)
然后使用以下方法验证您的数据:
JSON.parse(yourDataStr)
我不确定,但我认为fetch()
不适用于 NodeJS。 它只是浏览器中的本机功能(客户端 Javascript),因此在 NodeJS 中不起作用。 要解决这个问题,您必须下载 NodeJS 中的库,该库将支持 NodeJS 中的fetch()
,例如node-fetch 。
npm install node-fetch
node-fetch
fetch('') // Here add location for JSON file
.then(res => res.json())
.then(json => console.log(json));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.