gpt4 book ai didi

javascript - 在 MEAN.JS 应用程序中未使用 Angular $HTTP Get 读取 JSON 文件

转载 作者:行者123 更新时间:2023-11-30 16:12:11 25 4
gpt4 key购买 nike

我正在使用 MEAN.JS (www.meanjs.org) 开发一个 Web 应用程序,我正在尝试在我的 Controller 中使用 AngularJS $HTTP Get 请求和一个 JSON 文件,这样我就可以在一个文件中从中提取数据我的页面。出于某种奇怪的原因,从未读取 JSON 文件 (foo.json)。即使我只是尝试通过 http://localhost:3000/foo.json 访问文件它没有显示。它也不会在控制台中显示任何错误。我已将 JSON 文件放在我的模块、根目录、 View 目录等任何地方,随便你怎么说。仅当我使用较长的路径名(如“modules/core/json/foo.json”)时,我才会收到 Chrome 控制台错误,并显示“加载资源失败:服务器响应状态为 404(未找到)”错误。这是我的 Controller 代码:

angular.module('core').controller('FooController', ['$scope', '$http',
function ($scope, $http) {
$http.get('foo.json').success(function(data){
console.log(data);
$scope.products = data;
});
}
]);

FOO.JSON 文件放置在我的核心模块文件夹的根目录、 View 中,甚至应用程序的根目录中。

[
{

"id" : 3,
"name": "Orange Theme",
"description": "Consectetur adipiscing elit. Vestibulum condimentum turpis nec nunc scelerisque convallis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas id diam enim.",
"type": "Joomla",
"price": 12.99,
"images": [
{
"name": "orange.jpg"
}
]
},
{
"id" : 4,
"name": "Gray Theme",
"description": "Consectetur adipiscing elit. Vestibulum condimentum turpis nec nunc scelerisque convallis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas id diam enim.",
"type": "Joomla",
"price": 12.99,
"images": [
{
"name": "gray.jpg"
}
]
},
{
"id" : 5,
"name": "Purple Theme",
"description": "Consectetur adipiscing elit. Vestibulum condimentum turpis nec nunc scelerisque convallis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas id diam enim.",
"type": "html5",
"price": 9.99,
"images": [
{
"name": "purple.jpg"
}
]
}
]

我一直对这个感到沮丧,因为它看起来很简单!不确定它是否与未提供开箱即用的 JSON 文件有关,我需要在 Express 等中进行更改。我们将不胜感激。

最佳答案

由于无法从浏览器访问您的 JSON 文件,因此您似乎没有从 Node.js 提供静态文件。在您的 Node app.js 文件中,您需要初始化相关中间件以提供静态文件 - 例如,要提供 Node 应用程序内目录“public”中的文件,请添加:

app.use(express.static(path.join(__dirname, 'public')));

如果该文件位于您的 Node 应用程序的根目录中,则默认情况下无法通过 HTTP 访问它。因此,如果您将 JSON 文件放在名为 public 的目录中,并将上述行包含在您的 Node app.js 文件中,那么它应该可以通过 http://localhost:3000/foo.json 访问。

关于javascript - 在 MEAN.JS 应用程序中未使用 Angular $HTTP Get 读取 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36079557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com