cpprestsdk跨域問題解決方案

跨域問題可以採用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這個,並沒有效果。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章