简体   繁体   English

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

[英]How to use a node.js back-end server to interact with the front-end and a mongolab database?

I am building a website with a simple jquery/html/css front-end and a node.js server back-end. 我正在用一个简单的jquery / html / css前端和一个node.js服务器后端构建一个网站。 If my front-end has a function to request a user's information from the server like so: 如果我的前端具有从服务器请求用户信息的功能,例如:

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. 当我尝试从服务器请求时,我从firefox收到“混合内容”和/或“ corss来源”错误。 How can I have the node server running in the same domain as the rest of the site to avoid these errors? 如何使节点服务器与站点的其余部分在同一域中运行以避免这些错误?

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从任何地方处理请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在前端和后端 (Node.JS) 上使用 JS 的直观方式 - Intuitive Way to Use JS on Both Front-End and Back-End (Node.JS) 如何在node.js ejs模板中将变量从后端传递到前端 - How to pass variable from back-end to front-end in node.js ejs template 以响应方式将后端(通过Node.js中Express服务器上的Mongoose通过MongoDB通过MongoDB)链接到前端(引导程序或基金会)? - Linking back-end (MongoDB via Mongoose, on Express server in Node.js) to front-end (Bootstrap or Foundation) in a reactive way? NODE.JS:当表单提交出现后端错误时,如何拥有前端JS事件侦听器? - NODE.JS: How to have front-end JS event listener for when there is a back-end error on form submit? 从node.js后端控制前端javascript - Control front-end javascript from node.js back-end 无法从 React 前端向 Node.js 后端发送 POST 请求 - Can't send POST request from React front-end to Node.js back-end 从前端javascript向后端node.js发送POST请求 - Send POST request from front-end javascript to back-end node.js 如何使用后端 Node.js Express-Sessions 对 React 前端进行身份验证? - How to authentication React Front End with back-end Node.js Express-Sessions? 前端连接到后端 - Front-end connection to back-end 如何检测后端的前端操作? - How to detect the front-end actions at the back-end?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM