我在Angular中有一个客户端,而我的服务器是C ++。我知道最好使用节点,但是使用C ++服务器是一个限制。我正在使用在GitHub上找到的server。当我执行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 get请求并收到答案?
答案 0 :(得分:0)
HTTP specification需要\r\n
而不是\n
。
答案 1 :(得分:0)
看看https://github.com/Microsoft/cpprestsdk,以轻松创建c ++服务器。
关于正在使用的代码,您可能需要修改函数
(brand) (car)
要处理OPTIONS动词,大概是
var input = "BMW Volvo Saab";
var brand = input.split(" ");
var input2 = "car1 car2 car3";
var car = input2.split(" ");
var brandCars = brand.map((item,index) => `${item} ${car[index]}`);
console.log(brandCars);
然后实现新的options_d20函数,该函数可能需要您将以下标头添加到标头缓冲区中:
void handle_http_request(int fd)
但是我只是在猜测。