我想使用 Express 服务器创建简单的 React 应用程序。
我已经设置了简单的 express 服务器,如下所示。
package.json
{
"name": "hometask1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^8.0.4",
"babel-preset-env": "^1.7.0",
"eslint": "^5.9.0",
"eslint-loader": "^2.1.1",
"express": "^4.16.4",
"jest": "^23.6.0",
"npm-run-all": "^4.1.3",
"open": "0.0.5",
"webpack": "^4.26.0",
"webpack-dev-middleware": "^3.4.0",
"webpack-hot-middleware": "^2.24.3"
},
"proxy": "http://localhost:3000/"
}
index.js
const express = require('express')
const app = express()
const port = 3000
//app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Listening on port ${port}!`))
app.get('/express_backend', (req, res) => {
res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
});
我的文件夹结构如下:
projectfolder
node_modules
index.html
index.js
package.json
package-lock.json
现在,我想将这个 express.js 与我的 React 应用程序连接起来。以下是我的 react 应用程序。 (我不想使用create-react-app)
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello React</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1d3d0d3d4dd9cc2c5d0dfd5d0dddedfd4f1879f80849f81" rel="noreferrer noopener nofollow">[email protected]</a>/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
</body>
<script type="text/babel">
var helloWorld = React.createElement("h1", {}, 'Hello World!');
class HelloWorld extends React.Component {
render () {
return (
<h1>Hello World!</h1>
)
}
}
const container = React.createElement("div", {}, helloWorld, <HelloWorld /> );
ReactDOM.render(container, document.getElementById('root'))
</script>
</html>
任何帮助将不胜感激。
最佳答案
您需要根据基本 URL 请求 ( http://domain/ ) 从公共(public)目录提供文件
1。使 css、jss 文件可公开访问
将此行添加到您的 Express 服务器文件中
const app = express()
const port = 3000
app.use(express.static('public')) // this line
2。将 index.html
和 index.js
移动到 public
dir
你的目录结构看起来像
projectfolder
node_modules
public
index.html
index.js
package.json
package-lock.json
3。添加一个路由来服务索引文件
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/public/index.html'));
});
关于javascript - 连接 Express 和 React 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53466999/