c++ - 从 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 获取请求并收到答案?
解决方案
HTTP 规范要求\r\n
而不是\n
.
推荐阅读
- libgdx - 在设备上测试多个 libGdx 应用程序
- java - Active Directory:查询父级 AD 组的子域用户成员
- applescript - Applescript 在大苏尔莫名其妙地失败了
- java - 什么是替换只返回 false 的 if 语句墙的干净方法?
- vue.js - Vue - 强制更新 URL 中的新 id
- reactjs - InteliJ:Typescript 根据接口自动检查 {} 对象?
- amazon-web-services - 如何在不删除现有堆栈的情况下从 cloudformation 迁移到 CDK?
- tcl - 如何将 2 个列表合并为 TCL 中的键值对?
- jenkins - 在 Jenkinsfile 中的远程主机上执行 shell 命令
- ruby - 为什么我不能运行这个 ruby 文件?