Error: The specified JSON path for Ajax request could not be

Although my expertise lies in C++, I must confess that my knowledge about web development is quite limited. Therefore, please bear in mind that my question requires a simple answer.

Recently, I stumbled upon a fascinating C++ library for creating a web server on Github, which can be found here.

To test its functionality, I entered http://localhost:8080/ into my browser and was pleased to see that it worked perfectly. I also tested:

http://localhost:8080/info
http://localhost:8080/match/8796

Both of them functioned flawlessly as well.

However, when attempting to test Ajax/Json features, I encountered an issue. Despite using the following code in my Firefox browser console:

$.post( "json", {firstName: "John",lastName: "Smith",age: 25} );

not well-formed     json:1:18  ---> Could not open path /json

I also tried:

$.post( "string", {firstName: "John",lastName: "Smith",age: 25} );

But received a similar result.

Could you kindly point out where I might be making a mistake?


In essence, the C++ code hosts a server on port 8080 and responds to:

server.resource["^/string$"]["POST"]
server.resource["^/json$"]["POST"]
server.resource["^/info$"]["GET"]
server.resource["^/work$"]["GET"]
server.default_resource["GET"]

Below are some examples of client interactions:

    //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;

For those interested, you can access the `http_examples.cpp` file from this link.

#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>

// ... (rest of the code omitted for brevity)

Answer №1

After conducting a series of tests, I have found that the following steps work perfectly.

To execute, place the following code in an HTML file and open it in a browser:

<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>

Modify line #53's function in http_examples.cpp as follows:

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 OK\r\nContent-Length: " << name.length() << "\r\n" 
                  << "Access-Control-Allow-Origin: *" << "\r\n\r\n" 
                  << name;
    }
    catch(exception& e) {
        *response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << strlen(e.what()) << "\r\n\r\n" << e.what();
    }
};

Then, recompile using the command below and run the program again:

Make sure you are in the project directory before executing the next command.

make && ./http_examples

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When the click event is triggered, the second function guess() does not execute

I am currently developing a number guessing application. It consists of two functions, the first one called startGame() works correctly (it receives the maximum number and then disappears by adding the hidden class). However, the second function that is ...

How can one properly iterate through an HTML Collection in JavaScript?

I need help with creating a slider using JavaScript. The code I have written below calculates the widths of the slides, but it's throwing an error in the console. Can someone advise on how to properly loop through and assign width to these elements? ...

The background image fails to load in ReactJS application

Usually, I have no trouble finding solutions to my problems, but this time I'm really stuck - and I apologize in advance if my question seems silly or trivial. I am currently working on a simple React app where I need to set a background image for th ...

In React conditional return, it is anticipated that there will be a property assignment

What is the optimal way to organize a conditional block that relies on the loggedIn status? I am encountering an issue with a Parsing error and unexpected token. Can someone help me identify what mistake I am making and suggest a more efficient approach? ...

Load components dynamically and place them in a flexible position based on the context

UPDATE (After gaining a better understanding of the issue): I'm trying to display a component based on where the user clicks (specifically, which table row). Using ng2-smart-table, I've encountered an issue where there isn't a suitable sele ...

Time for the browser to evaluate javascript code has arrived

We are looking to enhance the speed at which our Javascript files load in the browser. Although our own Javascript files are simple and small, larger libraries like jQuery and KendoUI take a considerable amount of time to evaluate. We are interested in fin ...

Using ThreeJS to Apply Dual Materials to a Mesh Entity

With ThreeJS, it's possible to incorporate more than one material into an Object3D/Mesh as stated in the documentation. You can either utilize a single Material or an array of Material: Class declaration and constructor for Mesh TypeScript file (exce ...

The Net Core controller did not receive the ajax data as expected

My ajax call seems to be having an issue as the data is not getting passed to my controller correctly. Ajax $.ajax( { url: 'Playlist/AttachVideoToPlaylist', contentType: "application/json; charset=utf-8&q ...

Transfer the chosen language from the uib-dropdown language selector to the $scope variable

Here is a HTML template that allows the user to select a language: <div class="btn-group" uib-dropdown> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" uib-dropdown-toggle> ...

Struggling to align images side by side using HTML and CSS along with figcaption and buttons

Adding buttons below images on my webpage is proving to be a bit challenging. I tried using the figcaption tag, but it resulted in the images stacking on top of each other instead of side by side. **My HTML:** <section class="mostpurch"> ...

Step-by-step guide on creating a monochrome version of an image using automation

In WordPress, I have a logo parade where all logos are in color RGB. I really like the effect of having them appear as black and white initially and then transitioning to color when hovered over. I am familiar with using sprites for this effect, but it wo ...

What is the optimal parameter order when utilizing pre-curried functions and composition in JavaScript?

We have a simple, mathematically curried function for subtracting numbers: function sub(x) { return function (y) { return x - y; }; }; sub(3)(2); // 1 The function signature matches the obtained result. However, when function composition comes i ...

Issues with Fetch API and CORS in Web Browsers

Hello, I'm encountering an issue related to CORS and the Fetch API when using browsers. Currently, my setup involves running a NodeJS server built with Express on localhost:5000. This server responds to a GET request made to the URL /get_a, serving ...

Wizard for the advanced tab panel

I am facing a challenge with my advanced TabPanel Wizard. It consists of 4 tabs, each serving as its own form to allow for validation within the tab itself. The issue I am encountering is related to the validation behavior of non-rendered tabs. One proble ...

TinyMCE file multimedia upload feature allows users to easily add audio, video

I am looking to enhance the functionality of my TinyMCE Editor by enabling file uploads for audio/video and images. Although image uploading is functioning properly, I am encountering issues with other types of files. Despite setting up pickers throughout, ...

Troubleshooting: Why is Jquery unable to retrieve image height?

Having trouble using jQuery to find the actual height of the first image nested within a container. I can access the src attribute but not the height. Any suggestions on how to get the accurate height? Is it necessary to retrieve heights via CSS? Unfortu ...

React Router malfunctioning on production environment when integrated with an Express backend

My Single Page application is built using React for the frontend and Express for the backend. Within the application, there are two main components: and . The goal is to display the component when the "/"" URL is requested, and show the component for an ...

Troubleshooting problem with Angular's ng-repeat directive in dealing with varying number of child objects

I am currently dealing with tree-structured data where the parent nodes can have an indefinite number of children, and those children can also have an indefinite number of children, creating a deeply nested structure. While I have successfully formatted th ...

Exploring the integration of Styled-components in NextJs13 for server-side rendering

ERROR MESSAGE: The server encountered an error. The specific error message is: TypeError: createContext only works in Client Components. To resolve this issue, add the "use client" directive at the top of the file. More information can be found here i ...

Crisscrossed JavaScript Object: recursion and "intricate" conversion (using lodash)

Apologies for the complexity of this example; I've condensed it as much as possible to demonstrate what I'm aiming for I have a complicated structure that needs to be traversed and transformed based on certain conditions. Here's a brief exa ...