zoukankan      html  css  js  c++  java
  • jQuery的ajax请求express服务器返回数据

    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页面,会请求到数据!!!!

  • 相关阅读:
    29
    28
    27
    950. 按递增顺序显示卡牌
    25
    20190624
    409. 最长回文串
    636. 函数的独占时间
    LeetCode 1046. 最后一块石头的重量(1046. Last Stone Weight) 50
    LeetCode 942. 增减字符串匹配(DI String Match) 49
  • 原文地址:https://www.cnblogs.com/fqh123/p/11562835.html
Copyright © 2011-2022 走看看