没有找到Ajax Json路径
Ajax Json path not found
我对c++不差,但我对web的了解很糟糕,所以请考虑一下这个问题的答案将是简单的。
我在github上找到了一个用于web服务器的c++库。
当我在浏览器中输入http://localhost:8080/来测试它的HTML页面时,它可以正常工作。我还测试了:
http://localhost:8080/info
http://localhost:8080/match/8796
它们也很好。
然而,当我尝试测试它的Ajax/Json时,它不适合我使用以下代码在我的firefox浏览器控制台中。
$.post( "json", {firstName: "John",lastName: "Smith",age: 25} );
not well-formed json:1:18 ---> Could not open path /json
I tried
$.post( "string", {firstName: "John",lastName: "Smith",age: 25} );
,得到了相似的结果。
我哪里做错了?
简而言之,c++代码在端口8080上托管一个服务器,响应
server.resource["^/string$"]["POST"]
server.resource["^/json$"]["POST"]
server.resource["^/info$"]["GET"]
server.resource["^/work$"]["GET"]
server.default_resource["GET"]
客户端示例如下:
//Client examples
HttpClient client("localhost:8080");
auto r1=client.request("GET", "/match/123");
cout << r1->content.rdbuf() << endl;
string json_string="{"firstName": "John","lastName": "Smith","age": 25}";
auto r2=client.request("POST", "/string", json_string);
cout << r2->content.rdbuf() << endl;
auto r3=client.request("POST", "/json", json_string);
cout << r3->content.rdbuf() << endl;
http_examples.cpp[链接]
#include "server_http.hpp"
#include "client_http.hpp"
//Added for the json-example
#define BOOST_SPIRIT_THREADSAFE
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
//Added for the default_resource example
#include <fstream>
#include <boost/filesystem.hpp>
#include <vector>
#include <algorithm>
using namespace std;
//Added for the json-example:
using namespace boost::property_tree;
typedef SimpleWeb::Server<SimpleWeb::HTTP> HttpServer;
typedef SimpleWeb::Client<SimpleWeb::HTTP> HttpClient;
//Added for the default_resource example
void default_resource_send(const HttpServer &server, shared_ptr<HttpServer::Response> response,
shared_ptr<ifstream> ifs, shared_ptr<vector<char> > buffer);
int main() {
//HTTP-server at port 8080 using 1 thread
//Unless you do more heavy non-threaded processing in the resources,
//1 thread is usually faster than several threads
HttpServer server(8080, 1);
//Add resources using path-regex and method-string, and an anonymous function
//POST-example for the path /string, responds the posted string
server.resource["^/string$"]["POST"]=[](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
//Retrieve string:
auto content=request->content.string();
//request->content.string() is a convenience function for:
//stringstream ss;
//ss << request->content.rdbuf();
//string content=ss.str();
*response << "HTTP/1.1 200 OKrnContent-Length: " << content.length() << "rnrn" << content;
};
//POST-example for the path /json, responds firstName+" "+lastName from the posted json
//Responds with an appropriate error message if the posted json is not valid, or if firstName or lastName is missing
//Example posted json:
//{
// "firstName": "John",
// "lastName": "Smith",
// "age": 25
//}
server.resource["^/json$"]["POST"]=[](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
try {
ptree pt;
read_json(request->content, pt);
string name=pt.get<string>("firstName")+" "+pt.get<string>("lastName");
*response << "HTTP/1.1 200 OKrnContent-Length: " << name.length() << "rnrn" << name;
}
catch(exception& e) {
*response << "HTTP/1.1 400 Bad RequestrnContent-Length: " << strlen(e.what()) << "rnrn" << e.what();
}
};
//GET-example for the path /info
//Responds with request-information
server.resource["^/info$"]["GET"]=[](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
stringstream content_stream;
content_stream << "<h1>Request from " << request->remote_endpoint_address << " (" << request->remote_endpoint_port << ")</h1>";
content_stream << request->method << " " << request->path << " HTTP/" << request->http_version << "<br>";
for(auto& header: request->header) {
content_stream << header.first << ": " << header.second << "<br>";
}
//find length of content_stream (length received using content_stream.tellp())
content_stream.seekp(0, ios::end);
*response << "HTTP/1.1 200 OKrnContent-Length: " << content_stream.tellp() << "rnrn" << content_stream.rdbuf();
};
//GET-example for the path /match/[number], responds with the matched string in path (number)
//For instance a request GET /match/123 will receive: 123
server.resource["^/match/([0-9]+)$"]["GET"]=[&server](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
string number=request->path_match[1];
*response << "HTTP/1.1 200 OKrnContent-Length: " << number.length() << "rnrn" << number;
};
//Get example simulating heavy work in a separate thread
server.resource["^/work$"]["GET"]=[&server](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> /*request*/) {
thread work_thread([response] {
this_thread::sleep_for(chrono::seconds(5));
string message="Work done";
*response << "HTTP/1.1 200 OKrnContent-Length: " << message.length() << "rnrn" << message;
});
work_thread.detach();
};
//Default GET-example. If no other matches, this anonymous function will be called.
//Will respond with content in the web/-directory, and its subdirectories.
//Default file: index.html
//Can for instance be used to retrieve an HTML 5 client that uses REST-resources on this server
server.default_resource["GET"]=[&server](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
const auto web_root_path=boost::filesystem::canonical("web");
boost::filesystem::path path=web_root_path;
path/=request->path;
if(boost::filesystem::exists(path)) {
path=boost::filesystem::canonical(path);
//Check if path is within web_root_path
if(distance(web_root_path.begin(), web_root_path.end())<=distance(path.begin(), path.end()) &&
equal(web_root_path.begin(), web_root_path.end(), path.begin())) {
if(boost::filesystem::is_directory(path))
path/="index.html";
if(boost::filesystem::exists(path) && boost::filesystem::is_regular_file(path)) {
auto ifs=make_shared<ifstream>();
ifs->open(path.string(), ifstream::in | ios::binary);
if(*ifs) {
//read and send 128 KB at a time
streamsize buffer_size=131072;
auto buffer=make_shared<vector<char> >(buffer_size);
ifs->seekg(0, ios::end);
auto length=ifs->tellg();
ifs->seekg(0, ios::beg);
*response << "HTTP/1.1 200 OKrnContent-Length: " << length << "rnrn";
default_resource_send(server, response, ifs, buffer);
return;
}
}
}
}
string content="Could not open path "+request->path;
*response << "HTTP/1.1 400 Bad RequestrnContent-Length: " << content.length() << "rnrn" << content;
};
thread server_thread([&server](){
//Start server
server.start();
});
//Wait for server to start so that the client can connect
this_thread::sleep_for(chrono::seconds(1));
//Client examples
HttpClient client("localhost:8080");
auto r1=client.request("GET", "/match/123");
cout << r1->content.rdbuf() << endl;
string json_string="{"firstName": "John","lastName": "Smith","age": 25}";
auto r2=client.request("POST", "/string", json_string);
cout << r2->content.rdbuf() << endl;
auto r3=client.request("POST", "/json", json_string);
cout << r3->content.rdbuf() << endl;
server_thread.join();
return 0;
}
void default_resource_send(const HttpServer &server, shared_ptr<HttpServer::Response> response,
shared_ptr<ifstream> ifs, shared_ptr<vector<char> > buffer) {
streamsize read_length;
if((read_length=ifs->read(&(*buffer)[0], buffer->size()).gcount())>0) {
response->write(&(*buffer)[0], read_length);
if(read_length==static_cast<streamsize>(buffer->size())) {
server.send(response, [&server, response, ifs, buffer](const boost::system::error_code &ec) {
if(!ec)
default_resource_send(server, response, ifs, buffer);
else
cerr << "Connection interrupted" << endl;
});
}
}
}
我按照以下步骤进行了测试,它运行得非常完美。
将其放入html文件中,并在浏览器中运行:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$.post( "http://localhost:8080/json",
JSON.stringify({ firstName: "John", lastName: "Smith", age: 25 })
);
</script>
将第53行http_examples.cpp的函数修改为:
server.resource["^/json$"]["POST"]=[](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
try {
ptree pt;
read_json(request->content, pt);
string name=pt.get<string>("firstName")+" "+pt.get<string>("lastName");
*response << "HTTP/1.1 200 OKrnContent-Length: " << name.length() << "rn"
<< "Access-Control-Allow-Origin: *" << "rnrn"
<< name;
}
catch(exception& e) {
*response << "HTTP/1.1 400 Bad RequestrnContent-Length: " << strlen(e.what()) << "rnrn" << e.what();
}
};
然后,像这样重新编译,并重新运行:
确保在项目文件夹
make && ./http_examples
尝试通过http://localhost:8080/json更改相对url
相关文章:
- 在c++中使用nlohmann从类到json的转换
- 如何将更多文件夹添加到c++include路径
- 带有特殊路径部分的"std::filesystem::weakly_canonical"失败
- C++A*算法并不总是在路径中具有目标节点
- C++json插入数组
- nlohmann-json将一个数组插入到另一个数组中
- 如何使用curlpp通过POST方法上传文件和json数据
- JSON转换为nlohmann JSON-lib中的结构数组
- NLOHMANN 的 JSON 库将数组转换为结构向量
- 从函数角度看ID到文件路径的内部与外部映射
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 如何在 nlohmann 的 json 库中获取数组长度?
- boost xml parsingl将xml的路径作为变量发送
- 对于MacOS上的G++,如何添加默认的include目录/usr/local/include和默认的库搜索路径/usr
- 如何使用cppcheck处理半相对包含路径
- 在C++中设置基于操作系统的文件路径
- 保存json文件后如何返回文件路径
- 在Visual Studio Code(.json配置)中设置相对于工作区路径的c / c ++项目的包含路径
- 转义 json 的文件路径 (JsonCPP)
- 没有找到Ajax Json路径