C++ Post 请求库不发送 json 正文或表单数据

问题描述 投票:0回答:1

我正在尝试使用 elnormous 的 HTTPRequest 库通过我的 C++ 桌面应用程序与我的 NodeJS Express Rest API 进行通信。我在窗户上。

我尝试使用此库执行 json 正文和表单数据发布请求,但它不起作用。而且我不知道我是否做错了什么。

第一次尝试(使用表单数据发布请求):

    try {
        http::Request request{ "http://0.0.0.0/get-confirmations" };
        const std::string body = "shared_secret=" + account.shared_secret + "&identity_secret=" + account.identity_secret;
        const auto response = request.send("POST", body, {
            {"Content-Type", "application/x-www-form-urlencoded"}
        });
        std::cout << std::string{ response.body.begin(), response.body.end() } << '\n'; // print the result
    } catch (const std::exception& e) {
        std::cerr << "Request failed, error: " << e.what() << '\n';
    }

第二次尝试(使用 json body post 请求):

    try {
        http::Request request{ "http://0.0.0.0/get-confirmations" };
        const std::string body = "{\"shared_secret\":\"" + account.shared_secret + "\",\"identity_secret\":\"" + account.identity_secret + "\"}";
        const auto response = request.send("POST", body, {
            {"Content-Type", "application/json"}
        });
        std::cout << std::string{ response.body.begin(), response.body.end() } << '\n'; // print the result
    } catch (const std::exception& e) {
        std::cerr << "Request failed, error: " << e.what() << '\n';
    }

这就是我的 NodeJS Express Rest API 代码的样子:

import express from "express";

const port = 3000;

const app = express();

app.get('/', (req, res) => {
    const { name } = req.query;

    res.send('Hello world | Name: ' + name);
});

app.post('/get-confirmations', (req, res) => {
    console.log("query", req.query);
    console.log("body", req.body);

    const { shared_secret, identity_secret } = req.query;

    if (!shared_secret || !identity_secret) {
        return res.status(400).send('Missing shared_secret or identity_secret');
    }

    return res.send('Hello world | Shared Secret: ' + shared_secret + ' | Identity Secret: ' + identity_secret);
});

app.listen(port, () => {
    console.log(`[server]: Server is running at http://localhost:${port}`);
});
javascript c++ express http httprequest
1个回答
0
投票

原因可能会有所不同,具体取决于您所拥有的,我看不到您的代码有任何问题,但我可以给您一些可能有帮助的提示:

1-尝试从应用程序外部启动 API,例如 POSTMAN/ 2-尝试将端口 3000 添加到 API 请求中的 base_url 之后,如下所示 http://0.0.0.0:3000/ 3-确保您使用的端口 3000 未被任何其他可以创建服务器的应用程序使用,并检查 IP 地址是否可访问。

© www.soinside.com 2019 - 2024. All rights reserved.