Javascript 客户端路由协议
我正在尝试制作一个非常简单的客户端路由器。我的服务器是赤裸裸的:Javascript 客户端路由协议,javascript,express,Javascript,Express,我正在尝试制作一个非常简单的客户端路由器。我的服务器是赤裸裸的: 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 stati
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>
layout.js
(也是客户端):
const布局=`
-
`;
document.getElementById('my-app')。innerHTML=layout;
当我尝试加载
http://localhost:3000/register
,我在正文中得到了“我的应用程序”,这是我从服务器发送index.html
时所期望的。但我也得到了未捕获的语法错误:意外标记这有点旧,您可能已经发现了,但是index.html中的开始脚本标记缺少'>'。不。。。src
、integrity
和crossorigin
是脚本属性
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")
}
})
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;