node.js写接口实现前后端交互

1,387 阅读1分钟
                                 实现GET交互

前端

<button id="btn">请点击</button>
    <script type="text/javascript">
        $("#btn").click(function(){
            $.ajax({
                url: 'http://localhost:3000/checkUpdate',
                type: 'GET',
                success: function (data) {
                    console.log(data);
                },
                error: function (xhr, status, error) {
                    console.log('Error: ' + error.message);
                },
            });
        });
    </script>

后台

var express = require('express'); 
//引入express模块, 记得cnpm install express --save
var app = express();  //express对象

const verStr = {versionName : '2.0.0', versionCode : 200};  //版本检查返回的数据,假数据,自行修改

app.get('/checkUpdate', function(req, res){ //版本检查接口
    res.header('Access-Control-Allow-Origin', '*');
  
  res.send(JSON.stringify(verStr));
});

app.listen(3000, function(){  //服务端口监听
  console.log('server now listening at port 3000');
});
                                 实现POST交互

前端

   <button id="btn">请点击</button>
    <script type="text/javascript">
        $("#btn").click(function(){
            $.ajax({
                url: 'http://localhost:3000/newBusiInfo',
                type: 'post',
                data:{
                    awe: 12,
                    re: 34
                },
                success: function (data) {
                    console.log("data", data);
                },
                error: function (xhr, status, error) {
                    console.log('Error: ' + error.message);
                },
            });
        });
    </script>

后台

var express = require('express'); //引入express模块
var app = express();  //express对象
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
 
app.post('/newBusiInfo', urlencodedParser,  function(req, res){ //版本检查接口
    res.header('Access-Control-Allow-Origin', '*');
    console.log(req.body);
});

app.listen(3000, function(){  //服务端口监听
  console.log('server now listening at port 3000');
});