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

What is preventing the JQuery dialog from opening?

When I try to trigger a dialog box by pressing the enter key, it is not working as expected. Instead of opening the dialog, it just hides the text. Can someone help me understand what might be causing this issue? <!doctype html> <html lang="en" ...

Progressively updating elements one by one leads to updates

I am currently working on a webpage where one element ('.item--itemprice') updates its text through a function that I don't want to modify. My goal is to have another element ('.header--itemprice') update its text to match the firs ...

I'm having trouble seeing my remarks in the comment section

I've been working on setting up a comment section for my website, and I'm facing an issue with displaying the comments that users post in the database on the front end. When I try to retrieve and display the comment using a function, it doesn&apo ...

Is it possible to modify a specific index within an array stored in Firestore?

How can I modify a specific index within an array stored in Firebase/firestore? export const editComment = (comment) => { return (dispatch, getState, { getFirebase, getFirestore }) => { const firestore = getFirestore(); firestore.collec ...

What is the best way to fetch information from an API using Angular5 with Material2 components?

Here are the 'table.component.html' and 'table.component.ts' files where I am pulling data from an API to display in a table. Below is the object received from the API: [ {position: 1, name: 'Hydrogen', weight: 1.0079, sym ...

Continuously refresh the if/else statement

I'm currently facing an issue with my jQuery code regarding a responsive navigation bar. I am trying to add a class called 'mobile' to the navigation bar when it reaches close to the logo. Below is the snippet of my code: function respon ...

Why is there a delay in processing queries and requests in the MEAN Stack?

Recently, I've been diving into Node.js and experimenting with building a web app using the MEAN stack. One particular issue I encountered involved sending an array of strings (e.g., ["one", "two", "three"]) to the server side. In response, I attempt ...

Cypress and VueJS: How to target elements that are dynamically generated following a specific user interaction

I am currently testing a new feature where a button will only appear for the user to click after they have completed another action. Before proceeding with the action, I am verifying if the button exists: cy.get('span') .contains('Selec ...

Transmit an array in a post request with Node.js using the application/x-www-form-urlencoded content type

After attempting to send a post request to an API with post parameters as an array, I encountered difficulties. Here is how it can be done using cURL: curl http://localhost:3000/check_amounts -d amounts[]=15 \ -d amounts[]=30 I then tried to ach ...

Guide to dynamically setting a value in an input field using JavaScript's document.querySelector

My goal is to input a value using Javascript. Check out my project link! Click on "add to cart" and then proceed to checkout to reach the checkout page. I am trying to automatically add a Zipcode value to the checkout page. I attempted this method but it ...

Android openCV - not the typical opencv-android-sdk

In order to incorporate native C++ code or libraries into my Android application, I have a specific reliance on openCV. While I am familiar with the opencv-android-sdk and have researched tutorials on integrating it with Android Studio, I have found that t ...

Is there a way to utilize a value from one column within a Datatables constructor for another column's operation?

In my Typescript constructor, I am working on constructing a datatable with properties like 'orderable', 'data' and 'name'. One thing I'm trying to figure out is how to control the visibility of one column based on the va ...

Tips for managing unicode character sequences in C/C++ programming languages

What are some efficient and organized methods for managing unicode character sequences in C and C++? Additionally, how can you: -Retrieve unicode strings -Translate unicode strings to ASCII to conserve memory (if the input is solely ASCII) -Display uni ...

Is it allowed to use nested logical && operator in programming?

I am facing an issue with a .oct function I wrote for Octave. The problem seems to be related to the code snippet below - I'm unsure if nesting the logical && operator as shown is correct, or if it needs to be separated out using additional internal i ...

Avoiding Page Reloads with Ajax while Removing Entries from a Table in Laravel

I am encountering an issue where I can click the button, but it requires a refresh to execute the delete action. Is there something in my ajax code causing this problem and why is it refreshing? I want the button to instantly delete without the need for a ...

Accessing the first child node in JsTree

Is it possible to display only the first child of a list using the JStree plugin to create a tree? For example, if I have a list with 5 children, some of which have nested children, I am looking for a way to display only the first child of each <li> ...

In AngularJS, showcasing five elements at a time from an array containing 'n' items before looping back to the beginning

I'm a beginner in AngularJS and facing a scenario where I need to display 5 items from an array containing multiple items. The requirement is to initially show items 1-5 and then, after 2-3 seconds, add a 6th item at the top and remove the last item f ...

Typescript: Verifying the type of an interface

In my code, I have a function called getUniqueId that can handle two different types of interfaces: ReadOnlyInfo and EditInfo. Depending on the type passed to this function, it will return a uniqueId from either interface: interface ReadOnlyInfo { item ...

When data is stored in Internet Explorer's cache, any changes made are not being reflected in

Internet Explorer stores data in cache and even if there are changes, it may not reflect onclick. However, when I open the developer mode and try to access the same, then it works perfectly. This issue only seems to occur in IE as all other browsers work f ...

unable to properly assess the functionality of the timeout feature within the useEffect hook

I've been working on a lazyload image loader component that only loads images if they have been visible for more than 500ms. Although the functionality is working as expected, I'm facing challenges when it comes to writing a test to validate its ...