简体   繁体   中英

How to get data from MongoDB on client side using javascript/jQuery

I have written a code in bottle in python which gets data from mongodb and when the user request the url http://localhost:8080/index/test from bottle it will return the json result from mongoDB. it works fine when I point my browser to that url, I can see all the result on the browser.

However when I try to send a request from jQuery ajax I always get error, and the request never succeeds.

Has anyone ever done anything similar who can share their approach with me?

MY general question is, what the best way to get data from MongoDB from client side, when using bottle as the server. I have seen some example in Node.js but I want to use python as the server.

I have used this code.

                   $.ajax({
                    type: "POST",
                    url: "http://localhost:8080/hello/test",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",                        
                    success: function (response) {

                        console.log("success");
                    },
                    error: function (response){

                        console.log("failed");
                    }
                });*/

And I have also tried this :

                $.post( "http://localhost:8080/hello/test", d)
                  .done(function( response ) {
                      console.log("success");
                  });

no luck with any of these. I have also tried GET instead of post, but no luck.

This is kind of what I have in python side :

from bottle import route, run, template

@route('/hello/<name>')
def index(name):
    return {'status':'online', 'something':'blah blah'}

run(host='localhost', port=8080) 

Many thanks in advance.

First of all 'GET' is the better alternative since you are not passing any params to your DB.

Secondly on which port is your application running? You are adding 8080 to your request which lets me assume your app is running under a different port. JS is based on the Same Origin Policy that means if you want to access data from a different URL (different port = different url) it won't give you any repsponse data.

To make this work either make sure the python script is passing the information to your application directly or you have to implement Cross Origin Ressource Sharing . To do this you have to add a header to the response of your python (port 8080) script with the following content

Access-Control-Allow-Origin: localhost:XXXX //replace XXXX with your application port

EDIT: If you need to know how to activate COR check out this thread on stackoverflow: PY Bottle enable COR

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM