微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 未捕获的SyntaxError:在nodejs中出现意外的令牌

当我尝试提供客户端代码时,我收到以下屏幕截图错误.当我试图运行节点服务器/ server.js

enter image description here

以下是我的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请求.

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

解决方法:

通常发生的是当浏览器请求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.
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐