【问题标题】:Sending POST or GET request from Angular project to Python server从 Angular 项目向 Python 服务器发送 POST 或 GET 请求
【发布时间】:2020-08-21 12:56:33
【问题描述】:

我用 http.server python 库做了一个小服务器。

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()

我用一个简单的python脚本对其进行了测试

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 和 post 都由服务器接收。 然后我想用我的 Angular 项目发送请求。

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);
  }
}

我可以点击按钮,但服务器什么也没收到。 我是 Angular 的新手,所以我现在不知道我做错了什么。我的请求格式正确吗?

【问题讨论】:

标签: python angular post get


【解决方案1】:

如果我没记错的话,Angular 的 HttpClient getpost 方法都会返回一个您必须订阅的 Observable 对象,以便获取服务器发送的数据。

public postMsg() {
    var url = 'http://localhost:8080';
    var msg = "1234";
    var option = {'Content-Length' : msg.length, 'Content-Type': 'plain/text', 'body' : msg};
    this.http.get<any>('localhost:8080').subscribe((data) => console.log(data));
    this.http.request('POST', url, option).subscribe((data) => console.log(data));
  }

Angular 网站的http guide 相当完整,涵盖了很多主题,从发出 GET、POST、...请求、处理响应、拦截、传入和传出查询...

【讨论】:

  • 谢谢,我现在收到一个跨源请求错误,但它确实做了一些事情^^
  • 哦,是的,有道理。我想您的 Angular 服务器在 localhost:4200 上运行,而您的 python 在 localhost:8080 上运行?您应该添加 Access-Control-Allow-Origin HTTP 标头,但我不确定我知道在哪个请求中添加它... ^^'
  • 哦不,没关系,它适用于我的发帖请求。获取只是为了测试目的,所以没关系^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
  • 1970-01-01
  • 2018-02-22
相关资源
最近更新 更多