The dlib HTTP server displays websites in simple HTML format, without any JavaScript or CSS enhancements

Incorporating a small http server into my C++ program using the dlib library (http://dlib.net/network.html#server_http), my goal was to create a web interface by reading and returning an input HTML file upon request.

class web_server : public server_http
{
    const std::string on_request (
        const incoming_things& incoming,
        outgoing_things& outgoing
    )
    {
        ostringstream sout;
        sout<<get_file_contents("Seite.html");
        return sout.str();
    }

};

The functionality is successful, but when viewed in a browser, only the plain HTML site is displayed without any JavaScript/CSS elements. These are embedded within the HTML file as follows:

   <script type="text/javascript" src="scripte.js")>
   </script>
   <link rel="stylesheet" type="text/css" href="Style.css"> 

If I open the HTML directly in the browser, it looks fine. Thank you in advance.

Edit: With guidance from Davis King, I managed to get the JavaScript functioning, although the CSS is still not displaying correctly. I modified the response method to now send any requested file as a string: body of on_request:

ostringstream sout;
sout<<get_file_contents("Seite.html");
cout << "request path: " << incoming.path << endl;
string filename=incoming.path.substr(1,incoming.path.length()); 
if (incoming.path.substr(0,1) == "/" && incoming.path.length()>1) return get_file_contents(filename.c_str());
return sout.str();

Edit again: The issue has been resolved. Chrome indicated that the MIME type of the stylesheet file was text/html, when it should have been text/css. Once I adjusted my response method accordingly, everything worked as intended:

if (incoming.path=="/Style.css") outgoing.headers["Content-Type"] == "text/css";

In follow up, why do the CSS and JS files prompt a request, while the images referenced in the HTML do not? The images appear to be working despite the layout issues. Thanks anyways for the assistance, even though I am unable to upvote at the moment...

Answer №1

When the browser sends a request to the web server for Style.css and scripte.js files, it expects those specific resources in return. However, if the response only contains Seite.html, you need to modify your on_request method to handle this situation:

cout << "requested path: " << incoming.path << endl;
if (incoming.path == "/scripte.js")
    return get_file_contents("scripte.js");
else if (incoming.path == "/Style.css")
    return get_file_contents("Style.css");

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

Can anyone recommend a reliable JavaScript library for creating resizable elements?

I am looking to incorporate resizable functionality for a textarea. While I have experimented with jQuery UI's "resizable" feature, it doesn't quite meet my needs. I appreciate jQuery, but the resizable option falls short in allowing me to resize ...

Having trouble reaching the elements stored in an array?

As a beginner in Angular and JavaScript, I may be making some obvious mistakes so please bear with me. I have written this code that allows the selection of 2 text files and then combines them into a single array. $scope.textArray = []; $scope.textUpload ...

Lazy loading for natives not functioning, despite flags being turned on

I recently attempted to update my website by adding the new loading="lazy" attribute, following the example shown at: https://web.dev/native-lazy-loading While everything seemed to be working fine as demonstrated in the video, when I checked the waterfall ...

The error message "Each item within a list must be assigned a unique 'key' prop" is being displayed

At the moment, I'm immersed in a project that utilizes React, Next.js, and Ant-Design. However, during the development process, I encountered an error due to the absence of a unique key like so: Here's the detailed log of the error: Warning: Ea ...

What prevents an incomplete type from being converted to void?

What is the reason for the error that occurs in the code below? Why is it necessary for the type to be complete in order to be casted to void? struct Incomplete; class Class { virtual void foo(Incomplete &incomplete) { (void) incomple ...

Replace a function within a placeholder

Looking to validate the functionality of my custom Google Maps geocoder directive. In my code, I've set up a geocode constructor that I have already partially implemented: ... link: function(scope) { var map, geocoder, myLatLng, ...

The C++ program crashes while attempting to execute a function from a library

I recently added a new method to a C++ library, which compiles successfully and prints a log before returning. However, when trying to call this method from my program, the program abruptly quits without any warning or error message. Surprisingly, there is ...

Modal Pop-ups Failing to Open on Subsequent Attempts

My table consists of buttons on the right-hand side for a menu. The first button in the menu is supposed to open a modal box upon clicking. However, the first buttons in the subsequent rows do not function as expected and fail to open the modal. Refer to t ...

What is the best way to move between websites or pages without having to reload the current page using a selector?

Have you ever wondered how to create a webpage where users can navigate to other websites or pages without seeing their address, simply by selecting from a drop-down menu? Take a look at this example. Another similar example can be found here. When visit ...

What is the process of importing an HTML template into a Vue.js project?

I downloaded a template from the internet that I want to import into my vue project. This template includes HTML, CSS, and Javascript files of its own. How can I utilize vue-router to access the index.html file in this template without converting them into ...

How to use jQuery to target the second or any desired div element with a specific class

I'm having trouble with something seemingly simple Let's say we are looking for a class called .contentdiv, for example. I am trying to target the second or nth occurrence of the .contentdiv class in a document and retrieve the HTML of that spe ...

What is the most effective method for structuring code to display or conceal HTML based on the root in AngularJS?

Currently, I am utilizing Angular to create a quiz. The root for Questions is /#/questions/1. With a total of 6 questions, I am displaying and hiding HTML for each question based on the root. Here is how my code appears: Template <section ng-class="{ ...

Determine the presence of an element using its selector and retrieve a true or false value using jQuery or JavaScript

Is there a way to determine if an object is present on the page based on its selector? This method typically works: startpageentry = $('#' + startpageid) However, it does not return anything. I require a boolean value that can be used in an if ...

How can I utilize Django Rest Framework to send and retrieve an xlsx file?

I've been facing a challenge for quite some time now when it comes to sending a file to the client-side using django-rest-framework. I've managed to send it as a byte, but I'm struggling to handle it on the client-side for downloading it as ...

Failed to read the JSON file

Upon accessing The browser displays the following content: [ {"title": "simple node (no explicit id, so a default key is generated)" }, {"key": "2", "title": "item1 with key and tooltip", "tooltip": "Look, a tool tip!" }, {"key": "3", "title": "<span& ...

Error encountered when making a dynamic_cast while invoking a C++ API from Python

My current project involves trying to integrate a C++ API into a Python script. The code structure is as follows: class Engine { // Singleton Class responsible for heavy-duty work public: static Engine* getEngine(); bool init(); private: stati ...

The Jquery image on.load event seems to only function properly after performing a manual hard refresh of

Looking for a solution to replace loading text with a button only after the image has loaded onto the page. Utilizing on.load as follows: $('img.house').on('load', function() { $('.loading').hide(); $('# ...

"Enhance Your Website Navigation with a Expand/Collapse Menu Using

After stumbling upon this code that allows a menu to collapse when the user clicks on the minus sign, I noticed that it displays all the contents within the Main Item when the page first loads. My goal is to only show the Main Item when the page initially ...

Surround the image with a margin by wrapping text around it

Is it possible to display text in a div with a border and margin around an image using float: right? I have managed to get the text to wrap correctly around the image, but the border is positioned behind the image. UPDATE Here is a snapshot of how I wa ...

Updating the Title of a Page in Node.js

Is it possible to dynamically update the title of each page using NodeJS? The index.html file (located inside the public folder) looks like this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel= ...