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

时间:2022-03-14 06:48:01

I am building a website with a simple jquery/html/css front-end and a node.js server back-end. If my front-end has a function to request a user's information from the server like so:

我正在使用简单的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();
}

and my node server looks like this:

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

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");
        });
    }
}

why isn't it working? I get a 'mixed content' and/or 'corss-origin' error from firefox when I try to request from the server. How can I have the node server running in the same domain as the rest of the site to avoid these errors?

为什么不工作?当我尝试从服务器请求时,我从firefox收到“混合内容”和/或“corss-origin”错误。如何让节点服务器在与站点其余部分相同的域中运行以避免这些错误?

1 个解决方案

#1


2  

is really hard to read your code, I understand what you are trying to do, but let me suggest first a better structure easier to read, understand and implement more routes for your server, please check here:

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

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');
});

Also the lack of CORS support (https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) as you will need this in your use case for if you are planning to host serve static files consuming this service hosted in a different server, so lets use this module: https://www.npmjs.com/package/cors and it will allow express to process a request from anywhere.

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

#1


2  

is really hard to read your code, I understand what you are trying to do, but let me suggest first a better structure easier to read, understand and implement more routes for your server, please check here:

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

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');
});

Also the lack of CORS support (https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) as you will need this in your use case for if you are planning to host serve static files consuming this service hosted in a different server, so lets use this module: https://www.npmjs.com/package/cors and it will allow express to process a request from anywhere.

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