我正在尝试制作一个非常简单的客户端路由器。我的服务器无精打采:
const http = require('http')
const express = require('express')
const path = require('path')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
const app = express()
// Set static folder
app.use(express.static(path.join(__dirname, 'public')))
// Catch all 'get' requests, and respond with public/index.html
app.get('*', (req, res, next) => {
console.log(req.url)
if (req.url.indexOf('/api/') === -1) {
res.sendFile(path.join(__dirname, 'public/index.html'))
} else {
return next()
}
})
const port = process.env.PORT || 3000;
app.listen(port, function() {
console.log("Listening on port " + port)
if (process.send) {
process.send({ event:'online', url:'http://localhost:' + port})
}
})
module.exports = app;
我的index.html
也很瘦:
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
</head>
<body>
<div id="my-app">My App</div>
<script src="router.js"></script>
</body>
</html>
运行客户端的我的router.js
文件:
window.addEventListener('load', () => {
if (window.location.pathname === '/register') {
const myApp = document.getElementsByTagName('head')[0]
const layout = document.createElement('script')
layout.src = 'javascripts/layout.js'
myApp.appendChild(layout)
} else if (window.location.pathname === '/register/about') {
console.log("In about page")
}
})
layout.js
(也是客户端):
const layout = `
<div class="container">
<div class="row">
<div class="header clearfix">
<nav style="padding-top: 10px">
<ul class="nav nav-pills pull-left">
<li role="presentation">
<a href="/"><h3>My App</h3></a>
</li>
</ul>
<ul class="nav nav-pills pull-right">
<li role="presentation"><a href="/login">Login</a></li>
<li role="presentation"><a href="/register">Register</a></li>
</ul>
</nav>
</div>
</div>
</div>
`;
document.getElementById('my-app').innerHTML = layout;
当我尝试加载http://localhost:3000/register
时,我在主体中得到“我的应用程序”,这是我期望的,因为我是从服务器发送index.html
的。但是我也得到Uncaught SyntaxError: Unexpected token <
。我相信是因为返回的是HTML,而不是JS。
我的index.html文件设置是否正确作为应用程序的入口?