一、基础安装参考我的另一篇随笔

https://www.cnblogs.com/zhuxingqing/p/11526558.html

另在之前的基础上引入了jquery,方便使用ajax

 

二、前端代码

home.html

<!DOCTYPE html>
<html>
<head>
    <title>node home</title>
</head>
<body>
    <div id="wrap">home</div>
    <button onclick="window.location.href = '/city.html'">go to city</button>
    <script type="text/javascript" src="./static/jquery/jquery.min.js"></script>
    <script type="text/javascript">
        window.onload = function () {
            var wrap = $('#wrap')

            $.ajax({
                url: '/',
                type: 'GET',
                success: function (res) {
                    if (res.errno == 0) {
                        res = res.data
                        console.log(res)
                    }
                },
                error: function (msg) {
                    console.log(msg)
                }
            })
        }
    </script>
</body>
</html>

city.html

<!DOCTYPE html>
<html>
<head>
    <title>node city</title>
</head>
<body>
    city
    <div id="wrap"></div>
    <script type="text/javascript" src="./static/jquery/jquery.min.js"></script>
    <script type="text/javascript">
        window.onload = function () {
            var wrap = $('#wrap')

            $.ajax({
                url: '/api/city',
                type: 'GET',
                success: function (res) {
                    res = JSON.parse(res.data)[0]
                    console.log(res)
                    wrap.html(res.data)
                },
                error: function (msg) {
                    console.log(msg)
                }
            })
        }
    </script>
</body>
</html>

 

三、node代码

var express = require('express')

var app = express()
var port = 8090
var router = express.Router()

router.get('/', function (req, res, next) {
    req.url = '/home.html'
    next()
})

app.use(router)

var apiRouter = express.Router()
apiRouter.get('/city', function (req, res) {
    res.json({
        errno: 0,
        data: '[{"data":"cityssss"}]'
    })
})

app.use('/api', apiRouter)

app.use(express.static('./'))

module.export = app.listen(port, function () {
    console.log('Listening at http://localhost:' + port + '\n')
})

 

四、测试效果

home页面

 

点击按钮去city页面

 

 可以看到 已经将cityssss添加到wrap的div中~