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

问题描述 投票:1回答:2

我正在尝试学习构建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);
  },
});

至于我的Web服务器端,我也想从套接字编写它,因为我也想学习一些套接字编程,所以在另一个post之后,我在下面的服务器中编写了我的服务器,我的目标是只返回一个一个简单的字符串来证明这是可行的,但最终我希望能够返回一个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代码实时服务器扩展名运行网站时,出现以下错误:

已从CORS策略阻止从原点[http://localhost:5000/?_=1586356660223'访问'http://127.0.0.1:5500处XMLHttpRequest:在所请求的资源上没有'Access-Control-Allow-Origin'标头。

GEThttp://localhost:5000/?_=1586356660223net :: ERR_FAILED

我调查了“无Access-Control-Allow-Origin”错误,看来我无法在我的Ajax调用中以localhost提供url。如果不是,那么如果要与本地服务器对话,我应该在url字段中输入什么?

javascript ajax websocket webserver web-deployment
2个回答
2
投票

在响应头中添加Access-Control-Allow-Origin

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

1
投票

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

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

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,并使用该IP运行Flask或在同一网络中使用IP。

在AJAX中,您需要输入此URL才能将请求发送到。

如果有任何不正常的情况,请随时与我联系。

© www.soinside.com 2019 - 2024. All rights reserved.