I am trying to make a HTTP Post request through axios:
const onSubmit = (values) => {
console.log("submit", values);
// ctx.$i18n.locale = "en";
axios.post("http://192.168.3.2:8081", { // HTTP POST
name: state.name,
age: state.age,
message: state.message,
canvas: state.canvas,
});
};
And my backend server is like (Python):
class S(BaseHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_OPTIONS(self):
self.send_response(200, "ok")
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
# self.send_header("Access-Control-Allow-Headers", "X-Requested-With")
def do_GET(self):
logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
self._set_response()
self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))
def do_POST(self):
content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
post_data = self.rfile.read(content_length) # <--- Gets the data itself
logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",str(self.path), str(self.headers), post_data.decode('utf-8'))
self._set_response()
self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))
f = open(json.loads(post_data.decode('utf-8'))["name"]+ "-" + date.today().strftime("%m-%d-%Y") + ".txt", "w")
f.write(post_data.decode('utf-8'))
f.close()
I tested my backend server with Postman and it works fine, but it keeps returning this error in browser if I tried it with axios
POST http://192.168.3.2:8081/ net::ERR_EMPTY_RESPONSE
Uncaught (in promise) Error: Network Error
at createError (createError.js?2d83:16)
at XMLHttpRequest.handleError (xhr.js?b50d:84)
BTW: in server loggings, it seems like the server never receives a POST request, but only an OPTIONS request.
the request created by axios is a promise
you need to chain a .then
to it for the request to be actually sent
otherwise use the keyword async / await
in a newer browser
there are some examples in the README file of axios: https://github.com/axios/axios