跨域問題可以採用OPTIONS協議,在收到一方的OPTIONS請求之後,另一方應該設置好相應的headers。表示允許對應的服務的跨域請求。
1. cpprestsdk新增OPTIONS
m_listener.support(methods::OPTIONS, std::bind(&Command::handle_options, this, std::placeholders::_1));
2. OPTIONS方法添加headers
void Command::handle_options(http_request message)
{
http_response rep;
rep.headers().add(U("Access-Control-Allow-Origin"), U("*"));
rep.headers().add(U("Access-Control-Request-Method"), U("GET,POST,OPTIONS"));
rep.headers().add(U("Access-Control-Allow-Credentials"), U("true"));
rep.headers().add(U("Access-Control-Allow-Headers"), U("Content-Type,Access-Token,x-requested-with,Authorization"));
rep.set_status_code(status_codes::OK);
message.reply(rep);
}
建議添加上面的所有headers,因爲一開始我只添加
Access-Control-Allow-Origin
這個,並沒有效果。