[英]Node.js + Express - can't make app as SPA working
Having troubles with making my app to work as a Single Page Application. 使我的应用程序无法用作单页应用程序时遇到麻烦。 I'm using pug as a template engine.
我正在使用哈巴狗作为模板引擎。
Here is a general structure of the app: 这是应用程序的一般结构:
/app
/app/index.js // source of the app
/app/index.html
/app/bundledApp.js // from running webpack command
/app/components
/app/components/loginPage
/app/components/welcomePage
/app/config/routes.js
Here is my index.html file: 这是我的index.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="bundledApp.js"></script>
</body>
</html>
index.js file: index.js文件:
const express = require('express');
const app = express();
const server = require('http').Server(app);
const port = 3000;
app.set('view engine', 'pug');
app.use('/', routes);
server.listen(port, (err) => {
if (err) {
throw err;
}
console.log(':)');
});
router.js file: router.js文件:
const express = require('express');
const welcomePage = require('../components/welcomePage');
const login = require('../components/loginPage');
const router = express.Router();
router.route('/').get(welcomePage.welcomePage);
router.route('/login').get(login.loginPage);
module.exports = router;
Tried to add in index.js: 试图添加index.js:
app.use('/', express.static(__dirname + '/'));
app.get('/*', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
but when I run the app I get in the console: 但是当我运行该应用程序时,我进入了控制台:
bundledApp.js:736 Uncaught ReferenceError: require is not defined
I tried to use express-spa package ( https://www.npmjs.com/package/express-spa ), just required it in index.js and added: 我尝试使用express-spa软件包( https://www.npmjs.com/package/express-spa ),只是在index.js中需要它,并添加了:
app.use(spa());
but in the browser I get in the console while going to http://localhost:3000 : 但是在浏览器中,我进入http:// localhost:3000时进入控制台:
Uncaught SyntaxError: Unexpected token <
in bundledApp.js
在
bundledApp.js
My pug file looks like this for welcomePage view: 我的哈巴狗文件如下所示,用于welcomePage视图:
extends ../mainLayout/mainLayout // just a HTML5 template file
block title
title Welcome Player!
block content
a(href='/login') Go to login page
The app itself runs fine but I won't it to behave like a SPA page rather having pages being refreshed while going to different URLs. 该应用程序本身运行良好,但我不会表现得像SPA页面一样,而是在转到其他URL时刷新页面。 What am I missing in my approach?
我的方法中缺少什么?
Here is also a webpack.config.js file: 这也是一个webpack.config.js文件:
const webpack = require('webpack');
const path = require('path');
let config = {
entry: '/app/index.js',
target: 'node',
output: {
path: path.join(__dirname, '/app/index.js'),
filename: 'bundledApp.js'
}
};
module.exports = config;
Thanks for all the help guys! 感谢所有的帮助! :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.