【问题标题】:Js File in Node & Express Showing a HTML file insteadNode 和 Express 中的 Js 文件改为显示 HTML 文件
【发布时间】:2017-01-19 16:48:51
【问题描述】:

我正在尝试启动我的第一个 Node、Express 和 Angular 项目,但目前资产管道存在问题。我不确定这是否是由于我的文件夹结构造成的(我尝试按照在线教程进行操作,但不确定它的设置方式是否是最佳实践,所以我很乐意提供建议)但是当我尝试连接我的 js 文件时而是加载 index.html。我收到的错误是Uncaught SyntaxError: Unexpected token <

这是我的 server.js 文件:

// set up web server
var express = require('express');
var app = express();
var bodyParser = require("body-parser");

app.get('*', function (req, res) {
  res.sendFile(__dirname + '/views/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});

// listen (start app with node server.js)
app.listen(3000, function() {
  console.log("server going");
});

我截取了屏幕截图,以便您可以更详细地查看我的文件夹结构、index.html 文件和错误消息

感谢所有帮助,因为我对此一无所知!

【问题讨论】:

    标签: javascript html angularjs node.js express


    【解决方案1】:

    浏览器请求/public/js/app.js

    服务器运行这段代码:

    app.get('*', function (req, res) {
      res.sendFile(__dirname + '/views/index.html'); // load the single view file (angular will handle the page changes on the front-end)
    });
    

    ...因为* 匹配任何内容,包括/public/js/app.js,并将其发送给 HTML 文档。

    您必须编写服务器,以便它为浏览器提供浏览器要求的内容,而不是为所有内容提供index.html

    考虑为此使用the static module

    【讨论】:

    • 感谢 Quentin,我已将 app.use(express.static(path.join(__dirname, 'public'))); 添加到 server.js 文件中,并从文件中删除了 app.get('*' 路由,现在它正在工作。我找到了this 关于 express.static 的博客,它解释了如何很好地使用它。希望它将来可以帮助像我这样的其他菜鸟。
    猜你喜欢
    • 2014-07-30
    • 1970-01-01
    • 2022-11-21
    • 2017-07-17
    • 2017-01-12
    • 2015-08-14
    • 2016-10-18
    • 2013-07-23
    • 1970-01-01
    相关资源
    最近更新 更多