首页 > 解决方案 > 从 C++ 服务器获取 HTTP

问题描述

我在 Angular 中有一个客户端,而我的服务器使用 C++。我知道使用节点更好,但使用 C++ 服务器是一个限制。我正在使用我在 GitHub 上找到的这个服务器。当我执行 httpClient.get 请求时,它会返回错误。

服务器中的代码:

int send_response(int fd, char *header, char *content_type, char *body) {
   const int max_response_size = 65536;
   char response[max_response_size];

   // Get current time for the HTTP header
   time_t t1 = time(NULL);
   struct tm *ltime = localtime(&t1);

   // How many bytes in the body
   int content_length = strlen(body);

   int response_length = sprintf(response,
       "%s\r\n"
       "Access-Control-Allow-Origin: %s\r\n"
       "Access-Control-Allow-Methods: %s\r\n"
       "Content-Length: %d\r\n"
       "Content-Type: %s\r\n"
       "Date: %s" // asctime adds its own newline
       "Connection: close\r\n"
       "\r\n" // End of HTTP header
       "%s",

       header,
       "*",
       "POST, GET",
       content_length,
       content_type,
       asctime(ltime),
       body
    );

   // Send it all!
   int rv = send(fd, response, response_length, 0);

  if (rv < 0) 
      perror("send");

   return rv;
}

void get_d20(int fd) {
    char response_body[8];
    sprintf(response_body, "%d", 5);

    send_response(fd, "HTTP/1.1 200 OK", "text/plain", response_body);
}

这是我的客户代码:

public my_function(): void {
   let theResp;
   this.getServer().subscribe((resp) => {
       theResp = resp;
   });
   console.log('Return of get: ' + theResp);
}

public getServer(): Observable<any> {
   const httpOptions = {
    headers: new HttpHeaders({
      'Authorization': '*'
    })
   }
   return this.httpClient.get('http://SERVER_IP_ADRESS:3490/d20', httpOptions);
}

每次我尝试它时,我都会得到同样的错误:

zone.js:2969 OPTIONS http://SERVER_IP_ADRESS:3490/d20 0 ()
core.js:1601 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}

我知道这是一个 CORS 问题,但我找不到任何解决方案。我可以做些什么来达到我的 HTTP 获取请求并收到答案?

标签: c++httpservercorsangular-httpclient

解决方案


HTTP 规范要求\r\n而不是\n.


推荐阅读