简体   繁体   中英

Variable queries in node.js

I am trying to modify a query on my server side (node.js) that looks like this:

var http = require('http');
var query = "SELECT * FROM Users WHERE Email='Test.User@TestUser.com'";

This is the hardcoded query. I'm trying to do something like this (email being a variable pulled in from an input text area in an HTML doc):

var http = require('http');
var query = "SELECT * FROM Users WHERE Email=" + "'" + email + "'";

I'm using JQuery to handle the request like this from a javascript file:

$.ajax({
        url: "http://127.0.0.1:8000/",
        type: "POST",
        success: function(dataRcvd) {
            alert(dataRcvd);
        }

If I figure out how to do this I can dynamically update the var query with different SQL queries/stored procedures.

// server.js
var http = require('http');
function handler(req, res){
  console.log('Server got '+req.body.email);
  var query = "SELECT * FROM Users WHERE Email=" + "'" + req.body.email + "'";
  someAsyncSQLCall(query, function(rows){
    res.send(200, rows);
  });
};

http.createServer(handler).listen(3000);

//client.js
$.ajax({
        url: "http://127.0.0.1:8000/",
        type: "POST",
        data: {email: 'value' },
        success: function(dataRcvd) {
            alert(dataRcvd);
        }

This is an incredibly bad idea (string concatenation); anyone can post a SQL injection attack in your form and drop your database or do any number of other nefarious things.

I'm not sure what DB you're using, but most of them have a way of doing parameterized queries that sanitize you against these kinds of attacks.

Checkout node-postgres (pg module), which has examples of how to do it if you're using PostgreSQL.

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