背景:毕业设计,用C++做HTTP server
跨域导致的问题:
1,直接访问链接可以访问成功,在ajax中,返回状态为200,却跳到error所属的function中,下面代码数据结果为0,0,error
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
window.location.href="404/404.html"
},
2,debug可以看出,拦截跨域请求
跨域解决方法
static std::string header(std::string type, std::string Lenth){
std::string header{"HTTP/1.1 200 OK\r\nContent-Type: "+type+"\nCache-Control: no-cache\nContent-Length: "+Lenth+"\n"
"Access-Control-Allow-Origin: http://localhost:443\nAccess-Control-Allow-Credentials: true\n"
"Access-Control-Allow-Methods:GET,POST,PUT,POST\nAccess-Control-Allow-Headers:x-requested-with,content-type\n"};
return header;
}
static std::string sendMsg(std::string type, std::string &content, bool cookie = false, std::string cookieValue=""){
std::string all{};
all += header(type, std::to_string(content.length()));
if (cookie == true) {
all += "Set-Cookie:phone=" + cookieValue + "; domain=localhost; path=/\n";
}
all += "\n";
all += content;
all += "\r\n";
return all;
}