I made a little server with http.server python library.
import http.server
import socketserver
class SimpleHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
print("get")
def do_POST(self):
print("post")
content_length = int(self.headers['Content-Length'])
msg = self.rfile.read(content_length).decode('utf-8')
print(msg)
if __name__ == '__main__':
PORT = 8080
Handler = SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("-- stop --")
exit()
I tested it with a simple python script
import socket
def mypost():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", 8080))
txt = "1234"
post = "POST /test.txt HTTP/1.0\nContent-Length: " + str(len(txt)) + "\nContent-Type: plain/text\n\n" + txt
s.send(post.encode())
def myget():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", 8080))
post = "GET HTTP/1.0"
s.send(post.encode())
Get and post are both receive by the server. Then I want to send the requests with my angular project.
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'srp-send-request',
template: `
<button (click)="postMsg()">RUN</button >
`,
styles: [
]
})
export class SendRequestComponent implements OnInit {
constructor(private http: HttpClient) {
}
ngOnInit(): void {}
public postMsg() {
var url = 'http://localhost:8080';
var msg = "1234";
var option = {'Content-Length' : msg.length, 'Content-Type': 'plain/text', 'body' : msg};
var ret = this.http.get<any>('localhost:8080');
var ret = this.http.request('POST', url, option);
console.log(ret);
}
}
I can click on the button but the server receive nothing. I am new to Angular so I don't now what I done wrong. Are my request well formated ?