因此,我从使用create-react-app开始,并在我的机器上创建了一个react-app。我能够在本地主机上运行它并查看网页。接下来,我运行npm run build并让它构建./build目录。
然后,我创建了一个名为server.js的文件,其中包含以下内容:
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const auth_key = require('./correct_auth.json').auth;
const app = express();
app.disable('x-powered-by');
app.use(express.static(path.join(__dirname, 'build')));
app.get(
'*',
(req, res) => {
const headers = req.headers;
if (headers[`auth-token`] && headers[`auth-token`] === auth_key) {
console.log(`auth-token: ${headers[`auth-token`]}`);
res.sendFile(path.join(__dirname, `build`, `index.html`));
} else {
res.sendStatus(404);
}
}
);
app.listen(
process.env.PORT || 5000,
() => {
console.log(`Frontend start on localhost:5000.`);
}
);我的目标是只有在一个人有正确的auth-token头的情况下才能提供网页服务。但是,如果访问的站点没有正确的页眉,或者甚至没有指定页眉,仍然会提供主页服务。
我需要注意的是,我在DigitalOcean的Ubuntu服务器上运行了这个程序,并使用Nginx将其提供给localhost:5000。也就是说,我可以访问api.XXXXX.com来访问这个网站,不管我有什么标题,我总是会得到这个网站的服务。
我的目录结构如下所示:
build
correct_auth.json
node_modules
package.json
public
server.js
src发布于 2019-09-22 03:42:46
您的路线:
app.use(express.static(path.join(__dirname, 'build')));是在你检查标题之前,这样就可以在不检查标题的情况下为文件服务。
我建议您首先制作一个中间件来检查报头,如果它们不在那里,则返回适当的错误状态。
例如,将此放在第一位:
app.use((req, res, next) => {
const headers = req.headers;
if (headers[`auth-token`] && headers[`auth-token`] === auth_key) {
console.log(`auth-token: ${headers[`auth-token`]}`);
// continue on to other routes
next();
} else {
// 401 status is for not-authorized
res.sendStatus(401);
}
});发布于 2019-09-22 04:05:47
下面的代码工作正常,我在评论中提到了原因:
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const auth_key = require('./correct_auth.json').auth;
const app = express();
app.disable('x-powered-by');
// Put the header check middleware first, So all request mentioned after this code will go through this.
app.get(
'*',
(req, res) => {
const headers = req.headers;
if (headers[`auth-token`] && headers[`auth-token`] === auth_key) {
console.log(`auth-token: ${headers[`auth-token`]}`);
res.sendFile(path.join(__dirname, `build`, `index.html`));
} else {
res.status(404).send("Authentication failed");
}
}
);
// This should come after the middleware.
app.use(express.static(path.join(__dirname, 'build')));
app.listen(
process.env.PORT || 5000,
() => {
console.log(`Frontend start on localhost:5000.`);
}
);https://stackoverflow.com/questions/58043318
复制相似问题