What steps are needed to adjust the header access control to enable calling the database API in a web browser?

How can I fetch data from a MongoDB database using an Express API?

I am trying to use JavaScript for this task.

$scope.nmr=function(){
    $http.get("http://127.0.0.1:8081/Blogs")
    .then(function (response)
            {$scope.Blog = ((response.data).slice(0,8));
            });
            };

This is the HTML code that I am working with:

 <span style=" font-size:25px; ">معبد حتبسوت</span>
    <span style="margin-right:10%;" ng-repeat="x in Blog">
    <div star-rating rating-value="x.AvgRate" max="5"></div>
    </span>

In my server.js/Api file, I have the following code snippet:

 app.get('/Blogs', function (req, res) {
    MongoClient.connect(url, function (err, db) {
  if (err) {
    console.log('Unable to connect to the mongoDB server. Error:', err);
  } else {
    //We are connected.
    console.log('Connection established to', url);

    db.collection('Blog').find().toArray(function (err, result) {
    if (err) throw err

    console.log(result);
    res.end( JSON.stringify(result));
     })
     }
     });
     }) 

Although the data is returned in the console, I am encountering an error when trying to access it in the browser:

        [database server][1]

The error message reads: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at . (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)"

Answer №1

Here is the solution you need to implement:

const handleCrossDomain = function(req, res, next) {
        if ('OPTIONS' == req.method) {
          res.header('Access-Control-Allow-Origin', '*');
          res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
          res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
          res.send(200);
        }
        else {
          next();
        }
    };

    app.use(handleCrossDomain);

Learn more about enabling CORS in Express here

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 MongoDB connection in Ubuntu is functioning properly on the server side, but unfortunately, it cannot be accessed remotely

Attempting to retrieve the mongo message: It seems like you are trying to access MongoDB over HTTP on the native driver port. After setting up my server with mongodb, everything appears to be functioning correctly. When I try the following from the ser ...

Create a PDF document with the background of the input text included and printable

I am trying to find a way to make the background image of the input text appear when saving the page as a PDF (right-click, select "Print ...," and then "Save as PDF"). The page has a square background image that creates the effect of each character being ...

Arranging items in Angular based on selection from the database

i have data in table: Id, word, score , score_list. score are 0.4, 0.2, -0.5, 0, -0.3 .... in score_list i have positive, negative , neutral. How can i sort data with select by score_list? This is html <select class="form-control"> <option> ...

Encountering unexpected fetch requests to JSON files when using getStaticProps/getStaticPaths

My webpage seems to be functioning correctly, however I have noticed that in the console there are 5, 404 errors appearing on fetch requests. It's puzzling where these errors are originating from. Interestingly, these 404 errors only occur in the pro ...

APNS functionality is supported by APN providers, but it is not compatible with NodeJS in a production

I've set up a nodeJS script to send APNs. In development, it always works flawlessly. However, when I switch to production, the notifications never go through. Oddly enough, when I use the same notification ID with my production certificate in Easy Ap ...

The V-model fails to reflect changes when the checkbox list is updated

I am facing an issue with my checkboxes that are generated dynamically in a component using a v-for loop. Once a checkbox is checked, it is added to an array of selected checkboxes. The problem arises when a checked checkbox is removed - the v-model still ...

Do all types of data fall under the classification of objects?

Is every data type considered a distinct form of an Object? If I were to classify Array as a subtype of Object, what label would be appropriate for the elements contained within the Array? ...

The complete page gets re-rendered when Nuxt child routes are used

When I attempt to utilize child routes, my goal is to maintain specific data on the page while modifying other content. To illustrate this concept, I have created a straightforward example available at this link. After selecting "cat" and increasing the ...

The method models.User.fromURI is unsuccessful

When I try to call models.User.fromURI as shown below: models.User.fromURI("spotify:user:" + user, function (user) { $(div).html("<b ><a style=\"color:#FFFFFF\" href=\"spotify:user:" + user.username + "\">" + us ...

What is the best way to retrieve data once an action has been completed in Redux?

After triggering specific actions to update an array of objects in my global state, I want to send a PUT request to my Firebase database. This action can involve adding, deleting, or editing objects within the array, and I need to initiate the request righ ...

Nested arrays in the JavaScript programming language

Is this JavaScript code accurate: var options = []; options.push(["Tom","Smith"]); options.push(["Mary","Jones"]); where each item in options is a two-element array of strings. I plan to add items to options using a for loop. Furthermore, can I i ...

Identifying and troubleshooting issues in a React application operating within an nginx proxy

My React app is currently running on localhost:3000, while my Backend API is running on localhost:8181. To address cross-origin request issues and ensure compatibility, I have implemented an nginx reverse proxy setup for both the react app and backend API. ...

console displaying indentation problems with laravel and vue

I am currently utilizing Vue within Laravel and encountering a multitude of indentation errors in the console. https://i.sstatic.net/sfRec.png Here is an excerpt from my package.json file: "private": true, "scripts": { "clean": "rimraf public/buil ...

Surprising Outcomes of Negative Margin in jQuery Animation

Unique Project Summary I am currently working on a website that incorporates a sliding menu feature. I have successfully implemented this functionality, and the display remains consistent during the animation transitions for sliding the menu in and out. T ...

Navigating through the browser history will allow you to view the

Currently, I am working on the localhost/mysite/users page. This page displays a list of users that is fetched through an ajax request. However, I have encountered a strange issue. Whenever I navigate back and then forward again, the content on the localh ...

Exploring sentences using Python search queries

I need to efficiently search for terms in sentences stored in MongoDB. I have multiple dictionaries of terms, but the process of matching each term in each sentence precisely is slow. Is there a way to implement fuzzy matching or a similar approach to iden ...

Dispatching identification to controller after submission

I am encountering an issue with a page that contains the following code: <div class="col-sm-2 displaybutton"> <div data-point-to="displaysHeader"> @using (Html.BeginForm("Administration", "Home", FormMethod.Post)) ...

What is the technique for using JavaScript to implement styling on a <td> within an HTML table?

Can someone help me with applying JavaScript to an entire column in an HTML table? Here is the script I am currently using: I want to insert a line break after each comma in the Message column of the table. Can anyone point out what I'm doing wrong? ...

Exploring the benefits of thrift integration in Angular 2

Currently, I am working with the thrift protocol and have developed a basic app using Angular2. I create .js files by running thrift --gen js:ts file.thrift. Can anyone provide guidance on integrating Thrift into an Angular2 application? ...

The formValidation, previously known as BootstrapValidator, is causing issues with my form submission via Ajax, despite my efforts to update the code to work with

I recently upgraded the old BootstrapValidator to the new 0.6.0 release known as formValidation. Despite reading the documentation multiple times, I have been unsuccessful in finding the issue and need some assistance. Below are the CSS styles and scripts ...