服务器前后端学习理解

个人兴趣,突然想起来记录一下

1. 背景

想做一个最简单的网页,点击按钮后,访问服务器的redis数据库,读取一个为hello的值并显示
首先用js写了一个脚本,使用redis包,读取到了数据,并使用consol.log进行显示
随后,使用live server,在vscode中,运行了html文件,可以在网页中打开页面,显示一个段落文本和按钮
然而,在结合js脚本到html后,运行时无反应。通过浏览器调试,看到无法使用request,继而导入redis包也不可能

2. 思考

  1. 首先,上述的思路就是有问题的
    nodejs+js在服务器端运行,基于redis包进行访问没有问题。然而,使用html后,该文件是发给了用户端,他并没有直接访问数据库的权限,就算给其权限,也就暴露了数据库IP和账密,可能导致安全问题
    因此,正确的做法是,html的js脚本,请求服务端,服务端在读取redis数据后,响应给用户,再进行显示
    该做法的好处是,前后端隔离

3. 进一步问题

前面讲到用户js脚本向服务器请求,进行搜索,一个方法是AJAX,即A+JS+XML的方法,异步请求,再通过js脚本部分修改网页,使网页得到更新
很好,ajax可以访问html、txt、和php等,其中php作为编程语言,可以访问数据库如mysql,得到数据库的数据。
然而,php并不熟悉,我想用python或其他的语言作为服务器代码,去处理ajax的请求
虽然网上说所有代码都可以作为服务端代码,但是并未搜索到如何结合ajax+python的相关资料,是我的搜索不对吗?待解决

4. python作为后端

python作为后端,可以使用现有框架flash,第一篇的参考:ajax+flaskpython上手服务器

5. 代码

代码包括python代码和html,都运行。由于是在code server运行,请求ip会进行代理,需要合理修改
另外有redis数据库,对应修改IP或返回自定义的数据

  1. python服务端代码,命名为ajax_return.py
# 导入相关的包
from flask import Flask
import random
import redis


app = Flask(__name__)

# 对应ajax中url路径,响应/total_price路径的get和post请求,返回读取到的redis数据
@app.route('/total_price', methods=['GET', 'POST'])
def getRedisDat():
    value = ""
    try:
        r = redis.Redis(host='192.168.1.120', port=6379, db=0)
        value = r.get('test')
        r.close()
    except Exception() as e:
        print(e)

    return str(value)
    
# 主函数
if __name__ == '__main__':
	# 设置host与端口
    app.run(host = "127.0.0.1", port = 5000)

  1. html代码
<html>
<head>
    <meta charset="UTF-8">
    <title>ajax访问python服务端</title>

    <script>
        
    </script>

</head>

<body>
    <p id="id_p">
        你好呀
    </p>

    <input type="button" value="访问数据" id="but_1" onclick="doing()">


    <script>
        // 函数,使用ajax进行http请求,获得该http请求的响应,并显示在网页上
        function doing() {
                var xmlhttp;

                if (window.XMLHttpRequest)
                {
                    //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
                    xmlhttp=new XMLHttpRequest();
                }
                else
                {
                    // IE6, IE5 浏览器执行代码
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }

                xmlhttp.onreadystatechange=function()
                {
                    if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                        document.getElementById("id_p").innerHTML = xmlhttp.responseText;
                    }
                }

                xmlhttp.open("GET", "http://192.168.1.120:8443/proxy/5000/total_price", true);		// 请求的IP需要对应修改
                xmlhttp.send();
        }

    </script>
 
</body>

</html>

6. axios

ajax比较简单,但是会有一些缺陷,前端框架vue,使用的axios,而不是ajax。
因此,axios可以进一步学习。
区别在于:1. 需要在head中添加如下代码,导入axios
<!-- 使用axios要提前导入 --> <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
2. 部分IE浏览器不支持,但是也不差了
参考代码:

<html>
<head>
    <meta charset="UTF-8">
    <title>axios访问python服务端</title>

    <!-- 使用axios要提前导入 -->
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>


</head>

<body>
    

    <input type="button" value="使用axios访问服务器" id="but_1" onclick="doing_axios()">
    <p id="id_p">
        axios返回数据
    </p>
    <input type="button" name="" id="but_2" value="使用ajax访问服务器" onclick="doing()">
    <p id="id_p1">
        ajax返回数据
    </p>


    <script>
        function axios_get() {
            axios.get("http://192.168.1.120:8443/proxy/5000/get_test")
            .then(response => {
                console.log(response)
            })
            .catch(error => {
                console.log(error)
            })
        }


        // https://blog.csdn.net/weixin_53154312/article/details/130857155/
        function doing_axios() {

            // 发送GET请求
            axios.get("http://192.168.1.120:8443/proxy/5000/total_price")
            .then(response => {
                // 请求成功时的处理
                console.log(response.data);
                document.getElementById("id_p").innerHTML = response.data;
            })
            .catch(error => {
                // 请求失败时的处理
                document.getElementById("id_p").innerHTML = "err";
            });

        }

        // 函数,使用ajax进行http请求,获得该http请求的响应,并显示在网页上
        function doing() {
                var xmlhttp;

                if (window.XMLHttpRequest)
                {
                    //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
                    xmlhttp=new XMLHttpRequest();
                }
                else
                {
                    // IE6, IE5 浏览器执行代码
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }

                xmlhttp.onreadystatechange=function()
                {
                    if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                        document.getElementById("id_p1").innerHTML = xmlhttp.responseText;
                    }
                }

                xmlhttp.open("GET", "http://192.168.1.120:8443/proxy/5000/total_price", true);
                xmlhttp.send();
        }

    </script>
 
</body>

</html>

猜你喜欢

转载自blog.csdn.net/Hot_Ant/article/details/132605859
今日推荐