使用cpprest sdk发布json服务,与jeasyui接口

使用cpprest sdk发布json服务,与jeasyui接口,json,jquery-easyui,cpprest-sdk,Json,Jquery Easyui,Cpprest Sdk,我正在开发一个web服务,为异步树提供json对象。My HTML具有以下功能: <ul id="tt" method="POST" class="easyui-tree" url="http://w.x.y.z:1024/testrest"> </ul> ./testrest & Starting to listen HTTP/1.1 200 OK Content-Length: 44 Content-Type: application/json [{"i

我正在开发一个web服务,为异步树提供json对象。My HTML具有以下功能:

<ul id="tt" method="POST" class="easyui-tree" url="http://w.x.y.z:1024/testrest">
</ul>
./testrest &
Starting to listen
HTTP/1.1 200 OK
Content-Length: 44
Content-Type: application/json

[{"id":"1","state":"closed","text":"Hello"}]
这将干净地编译,我可以在linux服务器上通过以下方式启动服务:

<ul id="tt" method="POST" class="easyui-tree" url="http://w.x.y.z:1024/testrest">
</ul>
./testrest &
Starting to listen
HTTP/1.1 200 OK
Content-Length: 44
Content-Type: application/json

[{"id":"1","state":"closed","text":"Hello"}]
为了帮助调试,我一直使用
curl
在同一个linux服务器上直接充当POST客户机。我一直在使用以下命令发送内容长度为0的POST请求:

curl -i -X POST -H 'Content-Type: application/json' http://w.x.y.z:1024/testrest
curl的输出如下所示:

<ul id="tt" method="POST" class="easyui-tree" url="http://w.x.y.z:1024/testrest">
</ul>
./testrest &
Starting to listen
HTTP/1.1 200 OK
Content-Length: 44
Content-Type: application/json

[{"id":"1","state":"closed","text":"Hello"}]
“我的服务”中的控制台消息如下:

Handle POST

Handle_request
POST /testrest HTTP/1.1
Accept: */*
Content-Type: application/json
Host: w.x.y.z:1024
User-Agent: curl/7.29.0


jvalue must be null, setting some default values...
前两行对应于代码中的
跟踪
调用。中间部分由这段代码生成:

// Spit out the HTTP header to the console...
const auto HeaderString = request.to_string();
wcout << HeaderString.c_str() << endl;
在修改我的客户端
easyui树
HTML以指向web2pyurl之后,它完全填充了,我可以看到节点。我用curl点击web2py service.json代码只是想看看输出可能有什么不同:

HTTP/1.1 200 OK
Date: Mon, 23 Jan 2017 18:17:17 GMT
Server: Apache/2.4.6 (Red Hat Enterprise Linux) OpenSSL/1.0.1e-fips mod_wsgi/3.4 Python/2.7.5
X-Powered-By: web2py
Expires: Mon, 23 Jan 2017 18:17:18 GMT
Pragma: no-cache
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Content-Length: 99
Content-Type: application/json; charset=utf-8

[{"text": "Hello", "state": "closed", "id": "1"}]
除了内容标题非常不同之外,我怀疑有一行可能与之有关:

Content-Type: application/json; charset=utf-8
在对cpprest服务的调用中,curl的头输出不包括
charset=utf-8
。如果我使用
-o
开关将curl输出转储到文件中,我看不到编码之间有任何明显的区别。json格式中唯一不同的是一些额外的空格和顺序:

[{"text": "Hello", "state": "closed", "id": "1"}]    // web2py version
[{"id":"1","state":"closed","text":"Hello"}]         // cpprest version
我无法控制json字典的发送顺序,但我怀疑这与它有任何关系。作为值项前缀的额外空格似乎也不相关

我已经在microsoft.github.io/cpprestsdk/index.html上浏览了cpprest文档, 我找不到任何与设置输出编码有关的内容。
http_request::reply
有许多覆盖,包括设置内容类型的选项,我一直使用硬编码字符串调用它们,用于json正文和
json/application的内容类型;字符集=utf-8
,全部无效。无论如何,我都不知道如何将这些重写用于json::value对象,因此我认为这不是最佳路径,也不是这个cpprest库的可行用途

jeasyui javascript代码似乎是故意混淆的,我不相信能够弄清楚它对POST调用的回复做了什么。也许熟悉jeasyui的人可以指出调试async POST的可行方法


请帮忙

所以我知道发生了什么。在Chrome中打开开发者工具控制台,发现以下错误消息:

XMLHttpRequest无法加载。请求的资源上不存在“Access Control Allow Origin”标头。因此,不允许对源“”进行访问。

因此,这与我的json数据的格式或编码无关,而是json服务被识别为与生成客户端HTML的web服务器不同的资源,而Chrome正在阻止它。为了解决这个问题,我必须在发送回客户机的响应中添加一些头字段,并添加一个支持方法来处理来自任何可能需要它们的客户机的选项查询

在main()函数中,我添加了:

listener.support(methods::OPTIONS, handle_options);
然后我编写了相应的函数:

void handle_options(http_request request)
{
    http_response response(status_codes::OK);   
    response.headers().add(U("Allow"), U("POST, OPTIONS"));

    // Modify "Access-Control-Allow-Origin" header below to suit your security needs.  * indicates allow all clients
    response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
    response.headers().add(U("Access-Control-Allow-Methods"), U("POST, OPTIONS"));
    response.headers().add(U("Access-Control-Allow-Headers"), U("Content-Type"));
    request.reply(response);
}
最后,我必须向请求添加相同的头。在我的handle_请求中回复:

http_response response(status_codes::OK);

// Without these headers, the client browser will likely refuse the data and eat it
response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
response.headers().add(U("Access-Control-Allow-Methods"), U("POST, OPTIONS"));
response.headers().add(U("Access-Control-Allow-Headers"), U("Content-Type"));
response.set_body(answer);
request.reply(response);    
还有其他问题。。。最突出的事实是,jeasyui类
easyui_树
不会发布内容类型为
application/json
的数据。相反,它发布了一个内容类型为
application/x-www-form-urlencoded
,因此我必须添加一个函数来使用libcurl解析url编码。这还意味着将
request.extract_json()
替换为
request.extract_string()
,并对cpprest使用的相应lambda函数进行相关修改

这里是最后一个示例代码,可能对其他在这些领域工作的人有用。这是一个使用cpprest(在linux上,甚至更少)编写json服务的完整功能示例,该服务响应来自easyui_树的异步POST请求。依赖项:boost、cpprest和libcurl-devel

#include <boost/algorithm/string/replace.hpp>
#include <cpprest/http_listener.h>
#include <cpprest/json.h>
#include <curl/curl.h>
#pragma comment(lib, "cpprestlib" )

using namespace web;
using namespace web::http;
using namespace web::http::experimental::listener;

#include <iostream>
#include <map>
#include <vector>
#include <set>
#include <string>
using namespace std;

#define TRACE(msg)            wcout << msg 

void build_json( const utility::string_t &source, json::value &jvalue )
{
    // Use libcurl to unescape the POST body for us
    vector<string> splitvec;

    // We don't own the string created by curl_easy_unescape, so add a custom deleter
    string text = shared_ptr<char>( curl_easy_unescape( 0, source.c_str(), 0, 0 ), curl_free).get();

    // This works for this specific example of jeasyui, the class 'easyui-tree', which only passes id=... in the POST.  
    // Need custom handler to deal with more complicated data formats   
    boost::split( splitvec, text, boost::is_any_of("="));       
    if( splitvec.size() == 2 )
    {
        jvalue[splitvec.at(0)] = json::value::string(splitvec.at(1));
    }
}

void handle_request(http_request request, function<void(const json::value &, json::value &, bool)> action)
{
    json::value answer;

    auto objHeader = request.headers();
    auto sContentType = objHeader["Content-Type"];

    // Two cases: 
    // 1) The very first call from easyui_tree, when the HTML is first loaded, will make a zero-length POST with no 'Content-Type' in the header
    // 2) Subsequent calls from easyui_tree (e.g. when user opens a node) will have a Content-Type of 'application/x-www-form-urlencoded'
    // Nowhere does easyui_tree send json data in the POST, although it expects json in the reply
    if( sContentType.size() == 0 || 
        !strncasecmp( sContentType.c_str(), "application/x-www-form-urlencoded", strlen("application/x-www-form-urlencoded") ) )
    {
        request
            .extract_string()
            .then([&answer, &action](pplx::task<utility::string_t> task) {
                try
                {
                    const auto & svalue = task.get();
                    json::value jvalue;
                    if ( svalue.size() == 0 )
                    {
                        action(jvalue, answer, true);
                    }
                    else
                    {                       
                        build_json( svalue, jvalue );                       
                        action(jvalue, answer, false);
                    }
                }
                catch (http_exception const & e)
                {
                    wcout << "HTTP exception in handle_request: " << e.what() << endl;
                }
            })
            .wait();
    }
    else
    {
        // This Content-Type doesn't appear with easyui_tree, but perhaps it's still useful for future cases...
        if( !strncasecmp( sContentType.c_str(), "application/json", strlen("application/json") ) )
        {
            request
                .extract_json()
                .then([&answer, &action](pplx::task<json::value> task) {
                    try
                    {
                        const auto & jvalue = task.get();
                        if (!jvalue.is_null())
                        {
                            action(jvalue, answer, false);
                        }
                        else
                        {
                            action(jvalue, answer, true);
                        }
                    }
                    catch (http_exception const & e)
                    {
                        wcout << "HTTP exception in handle_request: " << e.what() << endl;
                    }
                })
                .wait();
        }
    }
    http_response response(status_codes::OK);

    // Without these headers, the client browser will likely refuse the data and eat it
    response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
    response.headers().add(U("Access-Control-Allow-Methods"), U("POST, OPTIONS"));
    response.headers().add(U("Access-Control-Allow-Headers"), U("Content-Type"));
    response.set_body(answer);
    request.reply(response);    
}

void handle_options(http_request request)
{
    http_response response(status_codes::OK);   
    response.headers().add(U("Allow"), U("POST, OPTIONS"));

    // Modify "Access-Control-Allow-Origin" header below to suit your security needs.  * indicates allow all clients
    response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
    response.headers().add(U("Access-Control-Allow-Methods"), U("POST, OPTIONS"));
    response.headers().add(U("Access-Control-Allow-Headers"), U("Content-Type"));
    request.reply(response);
}

void handle_post(http_request request)
{
    handle_request(
        request, 
        [](const json::value & jvalue, json::value & answer, bool bInitialize)
        {
            if( bInitialize )
            {
                // First time the tree is being loaded, first id will be 16, which will yield us 16 child nodes when it POSTs back
                json::value jreply;       
                jreply[U("id")] = json::value::string("16");
                jreply[U("text")] = json::value::string("Parent");
                jreply[U("state")] = json::value::string("closed");
                answer[0] = jreply;
            }
            else
            {
                // User has opened a node
                if( jvalue.type() == json::value::value_type::Object )
                {
                    if( jvalue.has_field( "id" ) )
                    {
                        auto & key = jvalue.at( "id" );
                        if( key.is_string() )
                        {
                            auto value = key.as_string();
                            int id = atoi(value.c_str());
                            stringstream ss;
                            ss << (id / 2);  // Each successive layer has half as many child nodes as the one prior
                            for( int i = 0; i < id; i++ )
                            {
                                json::value jreply;
                                jreply[U("id")] = json::value::string(ss.str());
                                jreply[U("text")] = json::value::string("Child");
                                jreply[U("state")] = json::value::string("closed");
                                answer[i] = jreply;
                            }
                        }
                    }
                }               
            }
        }
    );
}

int main()
{
    uri_builder uri("http://yourserver.com:1024/testrest");
    http_listener listener(uri.to_uri());

    listener.support(methods::POST, handle_post);
    listener.support(methods::OPTIONS, handle_options);
    try
    {
        listener
            .open()
            .then([&listener]()
                {
                    TRACE(L"\nStarting to listen\n");
                })
            .wait();

        while (true);
    }
    catch (exception const & e)
    {
        wcout << e.what() << endl;
    }
    return 0;
}
#包括
#包括
#包括
#包括
#pragma注释(lib,“cpprestlib”)
使用命名空间web;
使用名称空间web::http;
使用名称空间web::http::experimental::listener;
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
#定义跟踪(msg)wcout