Javascript HTTP POST请求获胜';不要让我定义上下文类型

Javascript HTTP POST请求获胜';不要让我定义上下文类型,javascript,c++,rest,http,asio,Javascript,C++,Rest,Http,Asio,我正在使用Ubuntu18.04和boost.asio向RESTAPI发送POST请求。当服务器接收到请求时,它会捕获它,但我似乎无法定义它的内容类型。我有一个函数collectRequestData,它应该解析请求的主体并将其返回到保存到MySQL数据库的位置。当我打印函数返回的内容时,它会打印null,它应该是发送的JSON文本。当我在调用函数之前打印“Content Type”时,当我认为它应该是“application/json”时,它会打印未定义的内容。我在这里的最终目标是,当我通过/

我正在使用Ubuntu18.04和boost.asio向RESTAPI发送POST请求。当服务器接收到请求时,它会捕获它,但我似乎无法定义它的内容类型。我有一个函数
collectRequestData
,它应该解析请求的主体并将其返回到保存到MySQL数据库的位置。当我打印函数返回的内容时,它会打印
null
,它应该是发送的JSON文本。当我在调用函数之前打印
“Content Type”
时,当我认为它应该是
“application/json”
时,它会打印未定义的内容。我在这里的最终目标是,当我通过
/file.o localhost 8080/license'{JSON formatted text}'
运行客户端代码时,它连接到localhost端口8080 path/license(它正确地连接到该端口),然后将JSON文本保存到MySQL数据库。这是不正确的,我很确定原因是
的“内容类型”
我对使用服务器和JavaScript不熟悉,所以如果有人看到我做错了什么,请指出。另外,如果您能提供额外的细节,以帮助我了解一个建议,将不胜感激


下面是我发送POST请求的客户端代码

#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;
using namespace std;

int main(int argc, char* argv[])
{
    cout << "main -start" << endl;
    try
    {
        boost::asio::io_service io_service;
        string ipAddress = argv[1]; //"localhost" for loop back or ip address otherwise, i.e.- www.boost.org;       
        string portNum = argv[2]; //"8000" for instance;
        string hostAddress;
        if (portNum.compare("80") != 0) // add the ":" only if the port number is not 80 (proprietary port number).
        {
            hostAddress = ipAddress + ":" + portNum;
        }
        else 
        { 
            hostAddress = ipAddress;
        }
        string wordToQuery = "";//this will be used for entry indexing
        string queryStr = argv[3]; //"/api/v1/similar?word=" + wordToQuery;
        string json = argv[4];

        // Get a list of endpoints corresponding to the server name.
        tcp::resolver resolver(io_service);
        tcp::resolver::query query(ipAddress, portNum);
        tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

        // Try each endpoint until we successfully establish a connection.
        tcp::socket socket(io_service);
        boost::asio::connect(socket, endpoint_iterator);

        // Form the request. We specify the "Connection: close" header so that the
        // server will close the socket after transmitting the response. This will
        // allow us to treat all data up until the EOF as the content.
        string typeJSON = application/json;
        boost::asio::streambuf request;
        std::ostream request_stream(&request);
        request_stream << "POST " << queryStr << " HTTP/1.1\r\n";  // note that you can change it if you wish to HTTP/1.0
        request_stream << "Host: " << hostAddress << "\r\n";
        request_stream << "User-Agent: C/1.0";
        request_stream << "Content-Type: application/json; charset=utf-8\r\n";
        request_stream << "Accept: */*\r\n";
        request_stream << "Content-Length: " << json.length() << "\r\n"; 
        request_stream << "Connection: close\r\n\r\n";
        request_stream << json;

        // Send the request.
        boost::asio::write(socket, request);

        // Read the response status line. The response streambuf will automatically
        // grow to accommodate the entire line. The growth may be limited by passing
        // a maximum size to the streambuf constructor.
        boost::asio::streambuf response;
        boost::asio::read_until(socket, response, "\r\n");

        // Check that response is OK.
        std::istream response_stream(&response);
        std::string http_version;
        response_stream >> http_version;
        unsigned int status_code;
        response_stream >> status_code;
        std::string status_message;
        std::getline(response_stream, status_message);
        if (!response_stream || http_version.substr(0, 5) != "HTTP/")
        {
            std::cout << "Invalid response\n";
            return 1;
        }
        if (status_code != 200)
        {
            std::cout << "Response returned with status code " << status_code << "\n";
            return 1;
        }

        // Read the response headers, which are terminated by a blank line.
        boost::asio::read_until(socket, response, "\r\n\r\n");

        // Process the response headers.
        std::string header;
        while (std::getline(response_stream, header) && header != "\r")
        {
            std::cout << header << "\n";
        }

        std::cout << "\n";

        // Write whatever content we already have to output.
        if (response.size() > 0)
        {
            std::cout << &response;
        }

        // Read until EOF, writing data to output as we go.
        boost::system::error_code error;
        while (boost::asio::read(socket, response,boost::asio::transfer_at_least(1), error))
        {
            std::cout << &response;
        }

        if (error != boost::asio::error::eof)
        {
            throw boost::system::system_error(error);
        }
    }
    catch (std::exception& e)
    {
        std::cout << "Exception: " << e.what() << "\n";
    }

    return 0;
}
app.post('/licence', function (req, res) {
    collectRequestData(req, result => {
        //console.log(request.headers['Content-Type']);
        console.log(result);
        sleep(5000);
        connection.query('INSERT INTO licence SET ?', result, function (error, results) {
            if (error) throw error;
            res.end(JSON.stringify(results));
        });
        //res.end(`Parsed data belonging to ${result.fname}`);
    });
});

function collectRequestData(request, callback) {
    console.log(request.headers['Content-Type']);
    const FORM_URLENCODED = 'application/json';
    if(request.headers['Content-Type'] === FORM_URLENCODED) {
        let body = '';
        request.on('data', chunk => {
            body += chunk.toString();
        });
        request.on('end', () => {
            callback(JSON.parse(body));
        });
    }
    else {
        callback(null);
    }
}

你缺了一条线

request_stream << "User-Agent: C/1.0";

request\u-stream您缺少行尾

request_stream << "User-Agent: C/1.0";

request\u stream我假设您正在为服务器使用nodeJS

nodejs以小写形式提供请求头

所以

当然,一旦你解决了@john发现的另一个问题

i、 e


你缺了一条线

request_stream << "User-Agent: C/1.0";

request\u stream我假设您正在为服务器使用nodeJS

nodejs以小写形式提供请求头

所以

当然,一旦你解决了@john发现的另一个问题

i、 e


你缺了一条线

request_stream << "User-Agent: C/1.0";

request\u stream感觉是web服务器问题,您可能不符合http协议规范。尝试使用boost::beast,它在boost 1.66及更高版本中提供。它是boost::asio之上的包装器,添加了高级web服务器和web套接字功能。您不需要为低级HTTP实现而烦恼


感觉是web服务器问题,您可能不符合http协议规范。尝试使用boost::beast,它在boost 1.66及更高版本中提供。它是boost::asio之上的包装器,添加了高级web服务器和web套接字功能。您不需要为低级HTTP实现而烦恼


首先,我认为你应该仔细检查服务器是否正确。提供一种方法:

curl "http://localhost:8080/licence" --data "{json format text}" -v
如果此命令响应的结果与您的相同,则是服务器的问题。
如果没有,请尝试在代码中汇编与curl相同的请求包内容,尤其是“\r\n”等等。

首先,我认为您应该仔细检查服务器是否正确。提供一种方法:

curl "http://localhost:8080/licence" --data "{json format text}" -v
如果此命令响应的结果与您的相同,则是服务器的问题。
如果没有,请尝试在代码中汇编与curl相同的请求包内容,尤其是“\r\n”等等。

正确的解决方案是@john和@Jaromanda X所说内容的组合,我还必须更改
const FORM_URLENCODED='application/json'
to
const FORM_URLENCODED='application/json;charset=utf-8'

正确的解决方案是@john和@Jaromanda X所说的结合,我还必须更改
const FORM_URLENCODED='application/json'
to
const FORM_URLENCODED='application/json;charset=utf-8'

一个问题是
内容类型
内容类型
不同。。。nodejs以小写形式向您显示标题一个问题是
内容类型
内容类型
不同。。。nodejs以小写形式向您显示标题