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

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

https://www.cnblogs.com/xiaojiangk/p/13753062.html

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

 

二、前端代码

1.home.html

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <title>node home</title>
 5 </head>
 6 <body>
 7     <div id="wrap">home</div>
 8     <button onclick="window.location.href = '/city.html'">go to city</button>
 9     <script type="text/javascript" src="./static/jquery/jquery.min.js"></script>
10     <script type="text/javascript">
11         window.onload = function () {
12             var wrap = $('#wrap')
13 
14             $.ajax({
15                 url: '/',
16                 type: 'GET',
17                 success: function (res) {
18                     if (res.errno == 0) {
19                         res = res.data
20                         console.log(res)
21                     }
22                 },
23                 error: function (msg) {
24                     console.log(msg)
25                 }
26             })
27         }
28     </script>
29 </body>
30 </html>

  2.city.html

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <title>node city</title>
 5 </head>
 6 <body>
 7     city
 8     <div id="wrap"></div>
 9     <script type="text/javascript" src="./static/jquery/jquery.min.js"></script>
10     <script type="text/javascript">
11         window.onload = function () {
12             var wrap = $('#wrap')
13 
14             $.ajax({
15                 url: '/api/city',
16                 type: 'GET',
17                 success: function (res) {
18                     res = JSON.parse(res.data)[0]
19                     console.log(res)
20                     wrap.html(res.data)
21                 },
22                 error: function (msg) {
23                     console.log(msg)
24                 }
25             })
26         }
27     </script>
28 </body>
29 </html>

 

三、node代码

 1 var express = require('express')
 2 
 3 var app = express()
 4 var port = 8090
 5 var router = express.Router()
 6 
 7 router.get('/', function (req, res, next) {
 8     req.url = '/home.html'
 9     next()
10 })
11 
12 app.use(router)
13 
14 var apiRouter = express.Router()
15 apiRouter.get('/city', function (req, res) {
16     res.json({
17         errno: 0,
18         data: '[{"data":"cityssss"}]'
19     })
20 })
21 
22 app.use('/api', apiRouter)
23 
24 app.use(express.static('./'))
25 
26 module.export = app.listen(port, function () {
27     console.log('Listening at http://localhost:' + port + '\n')
28 })

 

四、测试效果

  home页面

 

  点击按钮去city页面

 

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

 

posted @ 2020-09-30 10:13  陌小江  阅读(653)  评论(0编辑  收藏  举报