这可能是个愚蠢的问题,但我还找不到答案。:(我用create-react-app做app,服务器文件:
server.js
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const PORT = process.env.PORT || 3000;
const app = express();
const p = path.parse(__dirname);
app.use(express.static('public'));
app.get('/', (req, res) => {
const filePath = path.join(p.dir, 'src', 'index.js');
fs.readFile(filePath, {encoding: 'utf-8'},(err, data) => {
if (err) {
throw err;
}
res.send(data);
});
});
app.listen(PORT, () => {
console.log(`Started at port ${PORT}`);
});我试着从app src目录中读取index.js文件,但在浏览器中得到的都是纯文本。我只能运行公共目录中的静态文件。我做错了什么,我应该如何在节点中使用express运行react应用程序的js文件?
发布于 2020-06-24 03:44:17
您需要发送由react构建的index.html文件。浏览器只能打开html文件中的网页。
您需要首先使用npm run build构建react应用程序
然后用express来提供它,比如
app.get('*', (req,res) => {
res.sendFile('/build/index.html'); // wherever react creates the index.html
});发布于 2020-06-24 03:53:42
为了让你对express有一个基本的了解,
const express = require('express')
const app = express()
app.get('', (req, res) => {
res.render('index') // index is an html file or a template (ejs, hbs, etc..)
})
// You can't directly send js files
app.get('/info', (req, res) => {
res.render('info', {
title: 'info page',
message: 'welcome to the info page'
})
})
// You can't directly send js files
app.listen(3000, () => {
console.log('Server is up on port 3000.')
})如果您想要发送json
const leaderboardHistory = require("relativepath/leaderboardHistory.json")
app.get("/leaderboardhistory", function(req, res){
res.render("leaderboardhistory", {leaderboardHistory : leaderboardHistory});
});https://stackoverflow.com/questions/62542388
复制相似问题