我试图编写将运行由create-react-app
创建的React应用的节点服务器。实际上,发生了一些奇怪的事情,我不知道我在做什么错(以node server/index.js
的身份运行应用程序):
export default (app, dirname) => {
app.use(favicon(path.join(dirname, '..','build', 'favicon.ico')));
app.use(express.static(path.join(dirname, '..','build')));
// initialize routers
bootRotes(app);
if (process.env.NODE_ENV === AVAILABLE_ENVIROMENTS.DEVELOPMENT) {
expressBootDev(app, dirname);
} else {
app.get('/*', (req, res) => {
res.sendFile(path.join(dirname, '..', 'build', 'index.html'));
});
}
}
build
文件夹包含构建React应用,该应用创建了以下命令npm run build
在上传索引页后尝试上传静态内容时,发生了奇怪的事情。例如http://localhost:5000/static/js/2.30e86b6e.chunk.js
。浏览器仅在每个静态内容URL后添加/
,它变成http://localhost:5000/static/js/2.30e86b6e.chunk.js/
,当然,此URL与express.static中间件不匹配。
此外,我已经通过邮递员检查,URL GET http://localhost:5000/static/js/2.30e86b6e.chunk.js
最后带有/
的URL提供了预期的内容。
我与PRODUCTION env合作,这意味着expressBootDev不会产生任何影响。
有人有同样的问题吗?我花了整整一天的时间,不知道该如何解决问题。
在根逻辑几乎相同的根应用文件夹中创建简单代码并以node server.js
运行时,它可以按预期工作:
//server.js
const express = require('express');
const favicon = require('express-favicon');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
app.use(favicon(__dirname + '/build/favicon.ico'));
app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, 'build')));
app.get('/ping', function (req, res) {
return res.send('pong');
});
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(port);
我看不出任何主要区别
答案 0 :(得分:0)
var fs = require('fs');
var express = require('express');
var router = express.Router();
// GET: Sent some basic info for usage
router.get('/', (req, res, next) => {
var fname = __dirname + '/../public/index.html';
var val = fs.readFile( fname, 'utf8', ( err, data) => {
//send can only be called once, write can be called many times,
// in short res.send(msg) == res.write(msg);res.end();
res.writeHeader(200, {"Content-Type": "text/html"});
res.write(data);
res.end();
});
});
module.exports = router;
这是一个示例,该示例说明了如何使用node处理静态文件。 https://github.com/msatyan/ApiServe1/blob/master/routes/index.js 完整的项目是 https://github.com/msatyan/ApiServe1
仅供参考:带有HTTP1的Node.js不能有效地通过设计为静态文件提供服务,我相信node中对HTTP2的支持已解决了该问题。 HTTP1效率低下的原因是,它必须将在本机层读取的文件内容带到JavaScript层,然后通过HTTP服务器发送。