I have a Python echo server that sends a continuous stream of data when a client sends a GET request, as follows:
GET request for /?value=30
GET request for /?value=30
GET request for /?value=30
GET request for /?value=37
GET request for /?value=37
GET request for /?value=37
The snippet of the Python echo server, which uses the http.server library:
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
class S(BaseHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(text), str(self.headers))
self._set_response()
self.wfile.write("get_value: GET request for {}".format(text).encode('utf-8'))
Node.js code that logged the data response above:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
function httpGet(theUrl) {
let xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open("GET", theUrl, false);
xmlHttpReq.send(null);
return xmlHttpReq.responseText;
}
var i = 1
while (i ==1) {
console.log(httpGet('http://localhost:8080'));
}
I have successfully retrieved the data using a Node.js code however I wasn't successful in implementing it in React. How should I write a simple GET/fetch request in React? I'm very new to React and thanks for your guidance.
You can use the fetch-api to create HTTP request, here is react example:
componentDidMount() {
fetch('http://localhost:8080')
.then((res) => res.json() {
console.log(res)
})
}