mongoose中http server服务器解决“Access-Control-Allow-Origin mongoose”跨域问题

问题

使用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());

最终,返回的的串,看起来应该是这样:
mongoose中http server服务器解决“Access-Control-Allow-Origin mongoose”跨域问题_第1张图片

你可能感兴趣的:(Linux,http,服务器,网络协议)