构建本地 Web 服务器并将数据响应到 javascript

building a local web server and respond data to javascript

我正在尝试学习构建 Web 应用程序,该应用程序需要从 python 脚本生成的数据。谷歌搜索后。我找到了这个 link,看来我需要:

  1. 在 Python 中编写服务器端应用程序。定义 URL(路由)运行 是您的脚本。
  2. 在我的 Javascript 代码中,向步骤 1 中定义的 URL 发出 HTTP 请求。

在我的 java 脚本中,我有以下 ajax 调用,我不太确定 url 字段中的内容:

$.ajax({
  type: "get",
  url: "http://localhost:5000",
  cache: false,
  async: "asynchronous",
  dataType: "text",
  success: function (data) {
    //console.log(JSON.stringify(data));
    console.log("---->" + data);
  },
  error: function (request, status, error) {
    console.log("Error: " + error);
  },
});

至于我的网络服务器端,我想从套接字写它,因为我也想学习一些套接字编程,所以在另一个 post 我在下面写了我的服务器,在这个服务器中,我的目标只是 return 一个简单的字符串来证明这是可行的,但最终我希望能够 return 一个 json 对象 :

import socket
import threading
import json
import pdb

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.bind(('localhost', 5000))

sock.listen(1)

print("Listening at------>>> ", sock.getsockname())
connections = []

# Reply as HTTP/1.1 server, saying "HTTP OK" (code 200).
response_proto = 'HTTP/1.1'
response_status = '200'
response_status_text = 'OK'  # this can be random
res_status = "{} {} {}".format(response_proto, response_status,
                               response_status_text)

response_body_raw = "hello world"
# Clearly state that connection will be closed after this response,
# and specify length of response body
response_headers = {
    'Content-Type': 'text; encoding=utf8',
    'Content-Length': len(response_body_raw),
    'Connection': 'close',
}

response_headers_raw = ''.join('%s: %s\n' % (k, v) for k, v in
                               response_headers.items())


def handler(c, a):
    global connections
    while True:
        data = c.recv(1024)
        print(data)
        for connection in connections:
            # sending all this stuff
            connection.sendall(res_status.encode('utf-8'))
            connection.sendall('\n'.encode('utf-8'))
            connection.sendall(response_headers_raw.encode('utf-8'))
            # to separate headers from body
            connection.sendall('\n'.encode('utf-8'))
            connection.sendall(response_body_raw.encode('utf-8'))

        if not data:
            connections.remove(c)
            c.close()
            break


while True:
    c, a = sock.accept()
    print("Connected by------->>>", a)
    cThread = threading.Thread(target=handler, args=(c, a))
    cThread.daemon = True
    cThread.start()
    connections.append(c)

当我 运行 我的网站使用 VS 代码实时服务器扩展时,出现以下错误:

Access to XMLHttpRequest at 'http://localhost:5000/?_=1586356660223' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

GET http://localhost:5000/?_=1586356660223 net::ERR_FAILED

我查看了 No 'Access-Control-Allow-Origin' 错误,似乎我无法在 ajax 调用中将 url 作为 localhost 提供。如果不是,那么如果我想与本地服务器通信,我应该在 url 字段中输入什么?

在您的回复中添加 Access-Control-Allow-Origin header:

response_headers = {
  'Access-Control-Allow-Origin': '*',
  ...
}

因此,正如我的评论中已经提到的,我使用 Flask 服务器来处理 POST-通过 Ajax 发送的数据。

基本上,您可以这样设置服务器:

from flask import Flask, requests

app = Flask(__name__)

@app.route("/", methods=['POST', 'GET'])
def main_page():
    return "200"

if __name__ == "__main__":
    app.run(debug=True, host='192.169.178.62')

使用 host='192.169.178.62',您可以指定要 运行 您的 Flask 应用程序的 IP。 我建议您找出您的计算机 IP,然后将其用于 运行 Flask 或使用同一网络中的 IP。

在您的 AJAX 中,您需要输入此 URL 以将请求发送至。

如果有任何问题无法正常工作,请随时与我联系。