繁体   English   中英

'Uncaught SyntaxError: Unexpected token <' in Node.js

[英]'Uncaught SyntaxError: Unexpected token <' in Node.js

当我尝试提供客户端代码时,出现以下屏幕截图错误。 当我尝试运行node server/server.js

在此处输入图片说明

下面是我的server.js代码...

app.use(express.static(path.join(__dirname, "public")));
app.use(logger('dev'));
app.use(bodyParser.json({limit: '50mb'}));

app.all('/*', function(req, res, next){
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
    res.header("Access-Control-Allow-Headers", "Content-type,Accept,X-Access-Token,X-Key");

    if(req.method === 'OPTIONS'){
        res.status(200).end();
    } else {
        next();
    }

});

app.all("/api/v1/*", [require('./middlewares/validateRequest')]);
app.use("/", require("./routes"));

app.use(function(req, res, next){
    var err = new Error("Not found");
    err.status = 404;
    next(err);
});

在我的routes/index.js ,我有以下get request

router.get('*', function(req, res) {
    res.sendfile('./public/index.html');
});

通常当浏览器请求一个 JavaScript 文件时,服务器会发送一个 HTML 文件。 这是因为app.get('*'...这样的规则。所以我们需要告诉服务器先发送静态文件,然后声明规则,如下所示:

// Declare static folder to be served. It contains the JavaScript code, images, CSS, etc.
app.use(express.static('build'));

// Serve the index.html for all the other requests so that the
// router in the JavaScript application can render the necessary components
app.get('*', function(req, res){
  res.sendFile(path.join(__dirname + '/build/index.html'));
  //__dirname : It will resolve to your project folder.
});

我认为这可能是由您的/public/index.html文件引起的。

当您在index.html文件中包含 JavaScript 文件时,“src”属性存在一些问题。 因此它将返回一个“未找到”的 HTML 文件而不是实际的 JavaScript 文件。

我的文件夹结构

node(folder)
     server.js
     -client(f)
           -index.html
           -views(f)
           -js(f)
              -ctrl(f)
              -service(f)
              -app.js
              -state.js

app.use(express.static('client'));
app.get('/index.html', function (req, res) {

  res.sendfile(_dirname + '/index.html');

});

从浏览器调用: http : //127.0.0.1 : 1956/index.html

var server = app.listen(1956, function (req, res) {
    var host = server.address().address
    var port = server.address().port
    console.log("app listening at", host, port)
});

它对我来说很好用。

我找到了解决方案。 Node.js应用程序尝试编译 public 文件夹中的 JavaScript 文件,这是错误的; 您像这样定义了公共文件夹:

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

尝试通过添加特定的虚拟文件夹名称来使用虚拟目录定义它,如下所示:

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

这应该是工作;

我想部分问题出在您的router

在您的routes/index.jsget请求更改为

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

您是否也在使用gulp或类似的东西来管理您的资产? 如果不是,那么您如何为您的资产提供服务?

我建议您静态提供资产或使用gulp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM