我想用快递服务器创建简单的应用程序。
我已经安装了如下所示的简单快递服务器。
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应用关联。以下是我的应用程序。 (我不想使用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/babel-standalone@6.15.0/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>
任何帮助将不胜感激。
答案 0 :(得分:3)
您需要根据基本URL请求(http://domain/)从公共目录提供文件
将此行添加到您的快速服务器文件中
const app = express()
const port = 3000
app.use(express.static('public')) // this line
index.html
和index.js
移至public
目录您的目录结构看起来像
projectfolder
node_modules
public
index.html
index.js
package.json
package-lock.json
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/public/index.html'));
});