我尝试使用 cpp-netlib 实现 HTTP 服务器。其实我可以成功创建一个简单的http服务器。但现在我不知道如何为我的服务器设置 Access-Control-Allow-Origin 选项。
当我尝试通过 jQuery 客户端访问该服务器时发现了这个问题。当我尝试访问此服务器时,它返回如下错误。服务器在不同的网络中运行。
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
那么如何在此代码中设置“Access-Control-Allow-Origin:*”?我调查了 cpp-netlib 文件,但没有找到任何信息。
环境:
- Visual Studio 2010 专业版 32 位
- 提升 1.54.0
- cpp-netlib 0.9.4
我的代码:
#include <boost/network/protocol/http/server.hpp>
#include <iostream>
namespace http = boost::network::http;
struct hello_world;
typedef http::server<hello_world> server;
struct hello_world {
void operator() (server::request const &request,
server::response &response) {
server::string_type ip = source(request);
std::ostringstream data;
data << "Hello, " << ip << "!";
response = server::response::stock_reply(
server::response::ok, data.str());
}
void log(...) {
// do nothing
}
};
int main(int argc, char * argv[]) {
if (argc != 3) {
std::cerr << "Usage: " << argv[0] << " address port" << std::endl;
return 1;
}
try {
/*<< Creates the request handler. >>*/
hello_world handler;
/*<< Creates the server. >>*/
server server_(argv[1], argv[2], handler);
//server server_("127.0.0.1", 12344, handler);
/*<< Runs the server. >>*/
server_.run();
}
catch (std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}