如何使用node.js后端服务器与前端和mongolab数据库进行交互?

时间:2015-08-11 14:53:19

标签: javascript node.js mongodb web mlab

我正在使用简单的jquery / html / css前端和node.js服务器后端构建一个网站。如果我的前端具有从服务器请求用户信息的功能,如下所示:

function requestUser(email, password) {
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "http://localhost:8888/getUser/" + email + "/" + password, true);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
           console.log(xmlhttp.responseText);
        }
    }
    xmlhttp.send();
}

我的节点服务器如下所示:

var http = require("http"),
    mongojs = require("mongojs"),
    fs = require("fs"),
    url = require("url");
    express = require("express")
var server = http.createServer(requestHandler);
server.listen(8888);
var uri = "mongodb://<dbuser>:<dbpassword>@ds036698.mongolab.com:36698/alirodatabase";
var db = mongojs(uri, ["Papers", "Users"]);
console.log("node server running back end of app");
function requestHandler(request, response) {
    //request for user is .../getUser/<username>/<password>
    var path = url.parse(request.url).pathname;
    var details = path.split('/');
    if(details.indexOf("getUser") != -1) {
        console.log("recieved request for user");
        var user = db.Users.find({"email": details[details.indexOf("getUser") + 1],
                                  "password": details[details.indexOf("getUser") + 2]});
        user = user.toArray[0];
        response.writeHead(200, {"Content-Type": "text/json"});
        response.write(JSON.stringify(user));
    }
    else {
        fs.readFile("./index.html", function(err, file) {
            if(err) {
                return 
            }
            response.writeHead(200, {"Content-Type": "text/html"});
            response.end(file, "utf-8");
        });
    }
}

为什么它不起作用?我得到了一个混合内容&#39;和/或&#39; corss-origin&#39;我尝试从服务器请求时来自Firefox的错误。如何让节点服务器在与站点其余部分相同的域中运行以避免这些错误?

1 个答案:

答案 0 :(得分:2)

真的很难读懂你的代码,我理解你要做的是什么,但是让我先建议一个更好的结构,更容易阅读,理解和实现更多的服务器路由,请点击这里:

var express = require('express'),
  cors = require('cors'),
  app = express();

app.use(cors());

app.get('/getUser/:user/:passwd', function(req, res, next) {
  // Perform all mongo operations here using req.params.user and req.params.passwd
  // and in the callback send a response like the object below
  res.json({
    msg: 'This is CORS-enabled for all origins!',
    user: req.params.user,
    passwd: req.params.passwd
  });
});

app.listen(8888, function() {
  console.log('CORS-enabled web server listening on port 8888');
});

还缺少CORS支持(https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS),因为如果您计划托管使用托管在不同服务器中的此服务的服务静态文件,则需要使用此功能,因此我们使用此模块: https://www.npmjs.com/package/cors它将允许express从任何地方处理请求。