web后端和前端是怎么连接的
目录
web后端和前端是怎么连接的?
- web服务器(apache、tomcat等),网络协议(http、socket等),浏览器(chrome、FF、IE等)。浏览器发起建立连接请求,通过网络协议与服务器建立连接,服务器保持连接,获取浏览器想要的数据,服务器通过连接返回内容给浏览器,浏览器把数据呈现出来。2. 连接的协议一般是http,也有websocket。服务器以服务的方式存在,就像外卖店,你打个电话过去,人家就把饭菜送上门来了。3. web服务器访问数据库一样要使用网络连接,端口只是开放服务的入口而已,就像外卖的电话。
不是。
1 前后端通讯采用的是http协议传输数据;
2 这些数据需要有个统一的格式,告知前端开发者和后端开发者明白这些数据用来做什么;
3 最后前端js获得了json数据后,解析将其展示出来。
1 通过websocket通信 浏览器端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<a href="javascript:WebSocketTest()">test</a>
</div>
<script>
function WebSocketTest(){
var wsServer = 'ws://localhost:8000'; //服务器地址
var websocket = new WebSocket(wsServer); //创建WebSocket对象
websocket.onopen = function (evt) {
console.log("create connection")
websocket.send("hello");
};
websocket.onclose = function (evt) {
console.log("close connection")
};
websocket.onmessage = function (evt) {
console.log("receive: ",evt.data)
};
websocket.onerror = function (evt) {
console.log("error: ",evt.data)
};
}
</script>
</body>
</html>
服务器端
# coding=utf-8
from websocket_server import WebsocketServer
from urllib.parse import unquote
def new_client(client, server):
print("Client(%d) has joined." % client['id'])
def client_left(client, server):
print("Client(%d) disconnected" % client['id'])
def message_back(client, server, message):
# 这里的message参数就是客户端传进来的内容
print("Client(%d) said: %s" % (client['id'], unquote(message)))
results = "data from server"
# 将处理后的数据再返回给客户端
server.send_message(client, results)
# 新建一个WebsocketServer对象,第一个参数是端口号,第二个参数是host
# 如果host为空,则默认为本机IP
server = WebsocketServer(8000, host='')
# 设置当有新客户端接入时的动作
server.set_fn_new_client(new_client)
# 设置当有客户端断开时的动作
server.set_fn_client_left(client_left)
# 设置当接收到某个客户端发送的消息后的操作
server.set_fn_message_received(message_back)
# 设置服务一直运行
server.run_forever()
2 Ajax和flask通信方案 首先考虑服务器端API的设计:
#!flask/bin/python
from flask import Flask, jsonify
app = Flask(__name__)
tasks = [
{
'id': 1,
'title': u'title for id_1',
},
{
'id': 2,
'title': u'title for id_2',
}
]
@app.route("/")
def index():
return "Hello Flask!"
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
if __name__ == '__main__':
app.run(debug=True)
以上就写好了服务器端的RESTful API。运行上述代码,有:
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
@app.rount('/path')
控制路由,后面的函数控制内容。
通过服务器端或命令行工具访问上述接口,如果失败,考虑当前是不是正确运行了该文件,可关闭Pycharm打开的其他文件夹或者重启电脑。
使用接口可以成功访问到该API的信息,然而如果使用JavaScript访问该接口时有可能出现跨域的错误导致访问失败。这是由于html文件和python文件运行的端口不一致造成的。目前主流的解决方案是跨域资源共享(CORS,Cross-origin resource sharing),实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨源通信。其设置Access-Control-开头的方案实现跨域。
下面列出JavaScript的Ajax代码:
<!DOCTYPE html>
<html>
<head>
<title>Ajax Test</title>
<meta charset="UTF-8">
</head>
<body>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<div id="myDiv"><h2>AJAX :F12打开控制台查看信息</h2></div>
<button id="b01" type="button">submit</button>
<script>
$(document).ready(function(){
$("#b01").click(function(){
$.ajax({url: 'http://localhost:5000/todo/api/v1.0/tasks',
type:'GET',
success:function (res) {
console.log(res)
}
})
});
});
</script>
</body>
</html>
修改get_tasks()代码如下:
from flask import Response
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
data = json.dumps(tasks)
resp = Response(data)
resp.headers['Access-Control-Allow-Origin'] = '*'
resp.headers['Access-Control-Allow-Methods'] = 'GET,POST'
return res