如何防止来自服务器的响应直接显示在浏览器中?

时间:2019-04-18 08:06:44

标签: node.js express security server response

我正在为我的node.js服务器使用express.js框架。

这是我设置服务器的方式。

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var createUsers = require('./routes/users/createUsers');
var updateUsers = require('./routes/users/updateUsers');
var deleteUsers = require('./routes/users/deleteUsers');
var readUsers = require('./routes/users/readUsers');

var app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

var mysql = require("mysql");
//Database connection
app.use(function(req, res, next){
    res.locals.connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : 'password',
        database : 'project'
    });
    res.locals.connection.connect();
    next();
});

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/createUsers', createUsers);
app.use('/updateUsers', updateUsers);
app.use('/deleteUsers', deleteUsers);
app.use('/readUsers', readUsers);



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error.ejs');
});

var http = require('http');
module.exports = app;
var server = http.createServer(app);
server.listen(4000);

这是我的readUsers.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
    //console.log("pending data");
    res.locals.connection.query('SELECT id,name,email,username,address,phone,status FROM user', function (error, results, fields) {
        if (error) throw error;
        res.send(JSON.stringify(results));
    });

});

module.exports = router;

我的服务器在端口4000上监听。我的反应前端componentDidMount()函数使用axios.get("http://localhost:4000/readUsers")从数据库中读取数据,并且运行良好。

但是,如果我在浏览器中直接输入http://localhost:4000/readUsers,它将直接连接到数据库并读取所有用户数据并在浏览器中显示数据。这不是我想要的,因为每个人都可以在知道此地址的情况下读取我的数据。有什么办法可以防止这个问题?

2 个答案:

答案 0 :(得分:0)

使用POST而不是GET作为请求方法。

答案 1 :(得分:0)

将中间件添加到路由器。这是文档Router-level middleware

Express有很多中间件,其中之一是路由级中间件。该中间件处理用户和您的功能之间的任何事情。

这是我从文档中获取的示例。

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Hello, world!</title>
  
  </head>
  <body>


<button type="button" class="bg-transparent border-0 popover-tip mt-5" data-toggle="popover" data-content="The email address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by email.">Click here</button>


    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

  </body>
</html>

根据您的情况,您可以在请求之前添加一些权限验证。通常,它是一个API密钥,但可以是任何东西,标头中的秘密单词,秘密参数等等。 这是您的案例示例。

var app = express()
var router = express.Router()

// a middleware function with no mount path. This code is executed for every request to the router
router.use(function (req, res, next) {
  console.log('Time:', Date.now())
  next()
})

// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
router.use('/user/:id', function (req, res, next) {
  console.log('Request URL:', req.originalUrl)
  next()
}, function (req, res, next) {
  console.log('Request Type:', req.method)
  next()
})