angularjs - 在 View 中看不到我的 html 文件

标签 angularjs node.js express mean-stack

我正在尝试运行一个基本的 MEAN 应用程序。我的应用程序无需 Angular 部分即可运行。 但是当我包含 Angular 时,我看不到“view”文件夹中的 HTML 页面。

这是我的服务器:

var express=require('express');
var path=require('path');
var bodyParser=require('body-parser');

var index=require('./routes/index');
var tasks=require('./routes/tasks');
var port=3000;
var app=express();

/*View engine*/
app.set('views',path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.engine('html',require('ejs').renderFile);

/*View static folder*/
app.use(express.static(path.join(__dirname, 'client')));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use('/',index);
app.use('/api',tasks);
app.listen(port, function(){
    console.log('The application is running on port '+port);
});

这是我在“routes”目录下索引的路线:

var express=require('express');
var router=express.Router();

router.get('/',function(req, res, next){
    res.render('index.html');
})
module.exports=router;

我的 Angular 代码位于 client/app 目录中。 当我在终端的 myapp/client 目录中时,我正在输入 npm start 。 我收到“Can't get/”,并在终端中看到“404 GET/index.html”

有什么想法吗?

最佳答案

这意味着当您打开根路由 (/ uri) 时,它将呈现 index.html 文件:

router.get('/',function(req, res, next){
    res.render('index.html');
});

这意味着您的 View 文件(在您的问题 index.html 文件中)位于 views 文件夹中:

app.set('views',path.join(__dirname, 'views'));

如果您希望 EJS 渲染 index.html,请将 index.html 文件放入 views 文件夹(而不是 client 文件夹) .

并直接打开您的应用程序:http://localhost:3000/


附注如果你想像这样打开index.html:http://localhost:3000/index.html

执行以下操作:

确保您的routes/index.js具有以下内容:

const
  express = require('express'),
  router = express.Router();

const renderViewFile = (filename) => (req, res) => res.render(filename);

router.get('/', renderViewFile('index.html'));
router.get('/index.html', renderViewFile('index.html'));

module.exports = router;

或者:将index.html文件放入client文件夹中,它将作为静态文件

关于angularjs - 在 View 中看不到我的 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42880158/

相关文章:

javascript - Angular (ui-router) 路由无法完全正常工作?无法直接访问 url 而不通过基本 url

javascript - AngularJS View Animation Mystery—elements render at wrong position 然后 resolve

Node.js 如何将 req.body 转换为字符串

node.js - React-router服务器端错误

javascript - ng-class 指令调用执行了两次

java - Angularjs 和 Java 服务器 - 从 Netbeans 运行时如何使用相同的端口?

ruby - 使用 Ruby 读取使用 Node.js 创建的 Zlib 字符串

node.js - 尽管存在数据,但在 GraphQL 查询中日期字段返回为 null

node.js - Mongoose save() 实际上并没有保存

javascript - NodeJS 使用 axios 可重用 HTTP 请求