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

本文详细介绍如何在Node.js环境中引入jQuery,实现前端Ajax请求,包括基础安装、前端与后端代码示例,以及测试效果展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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中~

 

转载于:https://www.cnblogs.com/zhuxingqing/p/11527535.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值