问题
使用mongoose
做http服务器,自己构造的浏览器端jquery
在访问server时,会遇到:
Access to XMLHttpRequest at 'http://127.0.0.1:8000/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
jquery
的程序:
$.get("http://127.0.0.1:8000",function(d)
{
alert(d);
});
解决:
在mongoose
返回响应串中,如下构造:
使用 mg_http_reply
char str[128] = "respnose hello";
mg_http_reply(c, 200,
"Access-Control-Allow-Origin: *\n"
"Access-Control-Allow-Methods: *\n"
"Access-Control-Allow-Headers: *\n",
"%s\n", str);
使用mg_printf
std::string str = "respnose hello";
mg_printf(c, "HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\n"
"Cache-Control: no-cache\n"
"Content-Length: %d\n"
"Access-Control-Allow-Origin: *\n"
"Access-Control-Allow-Methods: *\n"
"Access-Control-Allow-Headers: *\n\n"
"%s\n", str.length(), str.c_str());
最终,返回的的串,看起来应该是这样: