Accessing MongoDB through Apache Server with CORS on a Windows 7 environment

I am currently in the process of developing a prototype application that involves making an Ajax GET call using JavaScript on an HTML page. The setup I have in place is as follows:

Operating System: Windows/Apache Web Server (XAMPP) Database: MongoDB Browser: Chrome

All of these components are running on the same Windows7(32) machine. The MongoDB server and data are located in the C:\ path, while the Apache server is in the C:\XAMPP path. I can access the MongoDB server directly through the browser by making a call to:

localhost:28017/ database/ collection

This call returns the collection's data in JSON format without any issues.

However, when I attempt to run the same Ajax call in JavaScript via an HTML page, I encounter the following error message:

XMLHttpRequest cannot load http:// localhost:28017/ database/ collection. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:// localhost' is therefore not allowed access.

In an effort to resolve this issue, I made modifications and inspected my httpd.conf file where I set the following:

<Directory />
   Header always set Access-Control-Allow-Origin "*"    
   Header always set Access-Control-Max-Age "1000"
   Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type,
Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding"
   Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
AllowOverride none
Require all denied
</Directory>

I also verified that the headers_module is being loaded with the directive:

LoadModule headers_module modules/mod_headers.so

Despite these configurations, the workaround was unsuccessful. It seems that the port number differs between the HTML and the Ajax call (80 vs. 28017), resulting in a new domain.

Below is the script code used for the Ajax call:

var xhr = new XMLHttpRequest();
console.log("xhr open")
xhr.open("GET", "http://localhost:28017/ database/ collection/", false);
xhr.send();

Here are the response headers from the HTML call:

Accept-Ranges:bytes
Access-Control-Allow-Headers:X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE, PUT
Access-Control-Allow-Origin:*
Access-Control-Max-Age:1000
Connection:Keep-Alive
Content-Length:564
Content-Type:text/html
Date:Mon, 09 Jan 2017 23:47:06 GMT
ETag:"234-545b12ed82b40"
Keep-Alive:timeout=5, max=100
Last-Modified:Mon, 09 Jan 2017 22:49:41 GMT
Server:Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/5.5.38

And here are all the headers from the XHR call:

General
Request URL:http://localhost:28017/ database/ collection/
Request Method:GET
Status Code:200 OK

Response Headers
Connection:close
Content-Length:369
Content-Type:text/plain;charset=utf-8
x-action:
x-ns:database.collection

Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:localhost:28017
Origin:http:// localhost
Referer:http://localhost/ load_mongodb_data.html
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36

Any help or guidance on resolving this issue would be greatly appreciated.

Answer №1

Cross-Origin Resource Sharing (CORS) is a method that allows restricted resources to be requested from (shared with) another domain, hence the term "Cross-Origin". The owner of the resource determines who can access it - this is the key aspect of CORS, as access permission is controlled by the resource's domain.

In your scenario, the requesting page is on port 80, while the resource is on port 28017.

Imagine port 80 as representing your domain with its resources.

Picture port 28017 as belonging to someone else's domain, with resources you wish to utilize.

You cannot simply "enable CORS" on your domain and expect access to the resources on another domain; if that were the case, CORS would serve no purpose.

To resolve this, you must configure the Access-Control-* headers on the server operating on port 28017.

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

The length of the LinearProgress bar does not match the length of the navbar

Utilizing the LinearProgress component from Material UI, I created a customized ColoredLinearProgress to alter its color: import React, { Component } from 'react'; import { withStyles } from '@material-ui/core/styles'; import { LinearP ...

Unable to add personalized repository

Looking to implement a request-scoped cache for my repositories, inspired by Hibernate's first-level-cache. I have some ideas on how to achieve this and integrate it with typeorm-transactional-cls-hooked. For now, I've created a basic provider s ...

The loader fails to disappear even after the AJAX response has been received

I am currently working on a page that utilizes AJAX to display data. While the data is being fetched, I want to show a loading animation, and once the data has been retrieved, I want the loader to disappear. Below is a snippet of the code where I am attemp ...

Issues with mongoDB: retrieving the last row value based on a certain grouping criteria

I've encountered an issue with MongoDB. I'm trying to retrieve the last name of a row if it exists within a MongoDB document: { _id: Object... campaign: 1 total: 1 ...: . .. campaignName: "name of campaign"<br> }, { _id: Obj ...

How can I use the same popup button to open a different link in a new tab?

I have a situation where I am using a button to trigger an ajax html popup. What I want is for the same button, when clicked, to open another page in a new tab. Any assistance would be greatly appreciated. Below is the HTML code I am currently using: < ...

What is the best way to utilize purgeCss in conjunction with other module exports?

After reading the documentation, I want to integrate purgeCss into my NextJS project. The recommended configuration in the docs suggests updating the next.config.js file like this: module.exports = withCss(withPurgeCss()) However, I am unsure where exact ...

Top method in Angular 6 for verifying if a scrollable section has been scrolled to the very bottom

I am searching for a reliable solution in Angular 6 to determine whether a scrollable host component has reached its maximum scroll bottom. Despite my efforts, I have been unsuccessful in finding a functioning example of a function that can detect if a cu ...

Having trouble displaying images using ejs.renderfile

I've been struggling to generate a PDF from an EJS file with the image rendering correctly. Here is my setup: My app.js code snippet: let express = require("express"); let app = express(); let ejs = require("ejs"); let pdf = require("html-pdf"); let ...

jQuery: Function is not running as expected

I'm facing a challenge in executing a function twice, and I'm having trouble identifying the issue. Check out my JSFiddle at the following link: http://jsfiddle.net/g6PLu/3/ Javascript function truncate() { $(this).addClass('closed&apo ...

Is there a way to modify the colors of particles in GPUParticleSystem with Three.js?

I have encountered an issue where I am trying to add black particles in a white THREE.scene. Despite changing the spawn option color, there are still white particles present as if there is a base particle spawn color. The problem arises when I set a white ...

Best practices for maintaining relationships in a MongoDB database

I am just starting out with MongoDB and I have a Master Collection called user_group. A sample document from this collection is provided below: {group_name:"xyz","previlege":["Add","Delete"],...} Additionally, there is a second collection named user_deta ...

What is the best way to completely update an array in MongoDB?

Is there a way to update an array within an object with a completely new array? I've been struggling to find a solution. This is the query I am using: Supply.update({_id: ObjectId('5e767d23d6d4390b6468b27c')}, {$set: {supplyList: req.body ...

Using Three.js, the loaded mesh's position displays variation compared to a basic geometry mesh

I've been attempting to position a mesh at a specific location, but I'm facing difficulties in achieving the exact placement I desire. While I can successfully position a simple sphere so that its left-most point aligns with the left border of my ...

Highlighting menu elements when landing on a page and making another menu element bold upon clicking in WordPress

I've been searching extensively for a solution to this issue. I'm trying to make the menu item DE appear bold when entering the site, and if I click on EN, I want DE to return to normal (thin) font while EN becomes bold. You can find the site he ...

Exporting data from AngularJS to Excel is not functioning correctly in Internet Explorer. Additionally, the exported Excel file does not display properly in Firefox and

I have been attempting to Export a table from a jsp page to Excel using AngularJs. Is Angularjs not compatible with IE? I am also encountering this error SCRIPT5009: 'Node' is undefined In Chrome and Firefox, the Excel file only opens when save ...

What could be causing multiple executions of an Ajax post request?

My code snippet: $(document).ready(function(){ $("#mainbutton").click(function(){ $("#ajaxform").submit(function(e){ var info = $(this).serialize(); $.ajax( { ...

While using .map() to display videos from an array, the button ends up playing all videos instead of only the selected

Within this component, I am presenting an array of YouTube videos utilizing react-player. The issue I'm facing is that when the custom play button is clicked, all videos in the array play and pause instead of just the selected one. I am currently uti ...

detecting click or submission actions on iOS

Below is the HTML code for a form submit that has been modified to prevent refreshing on submission. Everything seemed to be working fine, until I encountered an issue with the submit button not functioning on iOS. The onsubmit event simply wouldn't ...

What is the process for implementing pagination in vue-tables-2 with a Laravel REST API?

I'm looking to implement pagination on Vue server-table using a Laravel endpoint. How can I achieve this? Below is my component setup: <template> <div> <v-server-table :columns="columns" url="/object/find" :options="option ...

Issues persist with uWSGI workers constantly dying and needing to be reloaded when using Django in conjunction with nginx and u

Our application utilizes mongodb for data storage. Within our python process (django app), we retrieve data from mongodb and generate an HttpResponse based on certain calculations. However, a challenge arises as the data retrieved from mongodb is significa ...