首页 > 解决方案 > cpprestsdk 通过 Postman 返回状态码 500 发布请求

问题描述

我有来自这个例子的代码的服务器

当我尝试通过 Postman 发送帖子(或获取、放置、删除)请求时,我得到了 500 个服务器代码响应(内部错误),是什么导致了问题

#include <cpprest/http_listener.h>
#include <cpprest/json.h>
#pragma comment(lib, "cpprest_2_10")

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

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

void handle_request(
    http_request request,
    function<void(json::value&)> action)
{
    auto answer = json::value::object();

    request
        .extract_json()
        .then([&answer, &action](pplx::task<json::value> task) {
        try
        {
            auto const& jvalue = task.get();
            wcout << answer.serialize() << endl;

            if (!jvalue.is_null())
            {
                action( answer);
            } 
        }
        catch (http_exception const& e)
        {
            wcout << e.what() << endl;
        }
            })
        .wait();

            wcout << answer.serialize() << endl;
            request.reply(status_codes::OK, answer);
}

void handle_post(http_request request)
{
    std::cout << "Something received" << std::endl;

    handle_request(
        request,
        [](json::value& answer)
        {
            answer[L"random"] = json::value::string(L"success");
        });
}



int main()
{
    http_listener listener(L"http://localhost/restdemo");

    listener.support(methods::POST, handle_post);
    try
    {
        listener
            .open()
            .then([&listener]() { std::cout << "LISTENING" << std::endl; })
            .wait();

        while (true);
    }
    catch (exception const& e)
    {
        wcout << e.what() << endl;
    }

    return 0;
}

这是我最小的可复制示例,当我在 Postman 中发布请求时,在服务器端我只看到“收到的东西”行。

我测试了服务器出错了

auto const& jvalue = task.get();

调试行在该行之前工作,在该行之后不工作。

邮递员设置

邮递员身体

标签: c++postmancpprest-sdk

解决方案


我的错误在于,我试图通过邮递员表单数据编码请求内容类型 json/application ,当我在原始部分中形成 json 时,它可以工作。答案的所有学分都归@Botje!


推荐阅读