HTTP从C++;服务器 我有一个角的客户端,我的服务器是C++。我知道使用节点更好,但是使用C++服务器是一种限制。我正在使用我在GitHub上找到的这个。当我执行httpClient.get请求时,它返回一个错误
服务器中的代码:HTTP从C++;服务器 我有一个角的客户端,我的服务器是C++。我知道使用节点更好,但是使用C++服务器是一种限制。我正在使用我在GitHub上找到的这个。当我执行httpClient.get请求时,它返回一个错误,c++,http,server,cors,angular-httpclient,C++,Http,Server,Cors,Angular Httpclient,服务器中的代码: 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
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);
}
我知道这是CORS的问题,但我找不到任何解决方案。我能做些什么来达到我的HTTPGET请求并得到答案?< P>需要<代码> \r\n>代码>而不是< >代码> \n>代码> .p/> 查看一下,以方便地创建一个C++服务器。
关于您正在使用的代码,您可能需要修改函数
void handle_http_request(int fd)
要处理选项动词,可能需要
else if (strcmp(request_type, "OPTIONS") == 0) {
if (strcmp(request_path, "/d20") == 0) {
options_d20(fd, body);
} else {
resp_404(fd, request_path);
}
}
然后实现新的options_d20函数,该函数可能需要添加到headers缓冲区,这些headers:
"Access-Control-Allow-Origin":"*"
"Access-Control-Allow-Methods":"GET, OPTIONS"
"Access-Control-Max-Age":"3600"
"Access-Control-Allow-Headers":"Content-Type, Access-Control-Allow-Headers,Authorization, X-Requested-With"
但我只是在猜测。我在编辑中添加了
\r\n
类似的内容,但它不起作用。我仍然得到同样的错误。正如你正确推断的,这与CORS有关。在发出跨端请求之前,您必须正确实现兼容客户端发送的选项方法,或者使用不发送选项的客户端。如何实现选项方法?服务器应该返回什么?在这一点上,您必须参考您最喜欢的RFC。在实践中,C++是一种非常糟糕的语言来创建一个自托管的Web服务器,通常是很多的。简单地调用另一种语言的Web服务器中的C++代码就更容易了。
else if (strcmp(request_type, "OPTIONS") == 0) {
if (strcmp(request_path, "/d20") == 0) {
options_d20(fd, body);
} else {
resp_404(fd, request_path);
}
}
"Access-Control-Allow-Origin":"*"
"Access-Control-Allow-Methods":"GET, OPTIONS"
"Access-Control-Max-Age":"3600"
"Access-Control-Allow-Headers":"Content-Type, Access-Control-Allow-Headers,Authorization, X-Requested-With"