问题描述
当我尝试提供客户端代码时,我收到以下屏幕截图错误。当我试图运行节点服务器/ server.js
I am getting the below screen-shot error when i try to serve my client-side code. When i am trying to run node server/server.js
以下是我的server.js代码......
The below is my server.js code...
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
中,我有以下获取请求
。
Inside my routes/index.js
, i have the following for get request
.
router.get('*', function(req, res) {
res.sendfile('./public/index.html');
});
推荐答案
当浏览器请求javascript时,通常会发生什么文件,服务器发送一个html文件。这是由于 app.get('*'...
等规则。所以我们需要告诉服务器先发送静态文件然后声明规则,比如如下所示:
What usually happens is that when the browser request a javascript file, the server sends an html file. This is due to rules like app.get('*'...
. So we need to tell the server to send the static files first and then declare the rules, like shown below:
// 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.
});
这篇关于未捕获的SyntaxError:意外的令牌<在nodejs中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!