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

问题

使用mongoose做http服务器,自己构造的浏览器端jquery在访问server时,会遇到:

bash 复制代码
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的程序:

javascript 复制代码
$.get("http://127.0.0.1:8000",function(d)
{
   alert(d);
});

解决:

mongoose返回响应串中,如下构造:

使用 mg_http_reply

c 复制代码
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

c 复制代码
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());

最终,返回的的串,看起来应该是这样:

相关推荐
_下雨天.4 小时前
LVS负载均衡
服务器·负载均衡·lvs
mounter6257 小时前
【硬核前沿】CXL 深度解析:重塑数据中心架构的“高速公路”,Linux 内核如何应对挑战?-- CXL 协议详解与 LSF/MM 最新动态
linux·服务器·网络·架构·kernel
zzzyyy5387 小时前
Linux环境变量
linux·运维·服务器
kebeiovo8 小时前
atomic原子操作实现无锁队列
服务器·c++
CHHC18809 小时前
NetCore树莓派桌面应用程序
linux·运维·服务器
帮我吧智能服务平台10 小时前
装备制造智能制造升级:远程运维与智能服务如何保障产线OEE
运维·服务器·制造
handsomestWei11 小时前
Docker引擎API接入配置
运维·http·docker·容器·api
Tingjct11 小时前
Linux常用指令
linux·运维·服务器
daad77711 小时前
wifi_note
运维·服务器·数据库
IT界的老黄牛11 小时前
Linux 压缩命令实战:tar、gzip、bzip2、xz、zstd 怎么选?一篇讲清楚
linux·运维·服务器