html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <script>
        var params={val:""}
        $.ajax({
            type: 'GET',
            url: 'http://127.0.0.1:3000/',
            data: JSON.stringify(params),
            processData: false,//jquery是否是否处理data数据
            contentType: 'application/json',
            dataType: 'json'
        }).then(function(ret){
            console.log(ret);
        }).catch(function(err){
            console.log(err.statusText)
        })
    </script>
</body>
</html>

express服务器:

这里记得安装cors插件,为了解决跨域

npm install cors

express 服务器代码:

var express = require("express");//引入express
var cors = require('cors');
var app = express();//创建express实例
app.use(cors());//为了解决跨域问题
app.get("/",function(req,res){//定义路由 还有post delete方法 是express定义的
    var responseObject = {//也可以是数组 数组也会转化为json
        name:"大伟",
        age:27
    }
    res.json(responseObject)
});

app.listen(3000);
console.log("listening to port 3000")

启动这个服务器后,打开上面的html页面,会请求到数据!!!!

02-11 17:19