How the server built by Python socket returns JSON data to the browser

for a back-end server built with Python socket, the browser front end accesses the xx.py, under this server with AJAX. How can the JSON data be returned to the front end to facilitate the front end to obtain JSON data?
Please ask the great god who knows to help solve the doubt, thank you!

< hr >

here is the code:

import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1", 8080))
server.listen(50)
while True:

data, addr = server.accept()
info = b"{"id":"test", "psw":"123"}"

buffer = data.recv(1024)
data.send("HTTP/1.1 200 OK\r\nContent-type: text/html\r\n\r\n"+info)
data.close()
< hr >

problem solved

at the prompt of @ Lin_R, I try to return socket to the browser in the format of "http response header" + JSON format, so that I can get the JSON data correctly. The reason why it could not be obtained before is that the primary domain name of HTTP called by AJAX is the native domain name (127.0.0.1), while the domain name address of the server is (192.168. . ), which leads to the "cross-domain problem" and the browser does not allow AJAX to call JSON successfully. PS: is interested in looking up issues related to "AJAX cross-domain", hoping to help partners who have the same problems as me.
there is no doubt about this.

Jun.04,2021

if the backend is socket and you want to return the information to the front end, you can't directly return the json data, because you need to construct the response header of the http message, and then put the json data in it. Instead of this, it is better to set up a simple httpserver, directly at the back end so that you really only need to deal with json


.

import json

xxx.send (json.dumps ({'id':' test'}). Encode ()


can you put your Socket complete code

?
Menu