• 访问node后端接口示例(入门)


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

    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 + '
    ')
    })

    四、测试效果

    home页面

    点击按钮去city页面

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

  • 相关阅读:
    checkListbox的单选
    IP地址控件CIPAddressCtrl类的使用
    C++ Socket编程步骤
    环形缓冲区
    隐式链接和显示链接的区别
    memset、memcpy的使用方法!
    cetlm下载地址
    安装 GCC
    centos 配置代理
    make软件包安装
  • 原文地址:https://www.cnblogs.com/zhuxingqing/p/11527535.html
Copyright © 2020-2023  润新知