未捕获的SyntaxError:nodejs中的意外标记<

Sha*_*uru 8 javascript node.js express

当我尝试提供客户端代码时,我收到以下屏幕截图错误.当我试图运行节点服务器/ 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);
});
Run Code Online (Sandbox Code Playgroud)

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

router.get('*', function(req, res) {
    res.sendfile('./public/index.html');
});
Run Code Online (Sandbox Code Playgroud)

Jon*_*lez 14

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

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

// Serve the index.html for all the other requests so that the
// router in the javascript app 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.
});
Run Code Online (Sandbox Code Playgroud)


Oss*_*Oss 0

我想部分问题出在你的身上router

在您将请求routes/index.js更改get

router.get('/', function(req, res) {
    res.sendfile('./public/index.html');
});
Run Code Online (Sandbox Code Playgroud)

另外,您是否正在使用或类似的东西来管道化您的资产gulp?如果不是,那么您如何服务您的资产?

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