问题描述
当我尝试提供客户端代码时,出现以下屏幕截图错误.当我尝试运行 node server/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
中,我有以下内容用于 get request
.
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('*'...
之类的规则所致.因此,我们需要告诉服务器先发送静态文件,然后声明这些规则,如下所示:
Usually when the browser requests 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 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.
});
这篇关于“未捕获到的SyntaxError:意外令牌<"在Node.js中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!