我使用Nodejs创建了一个小型快递服务器,我目前能够处理单个帖子请求 - 检查用户是否存在。
我需要添加一个额外的帖子请求,这将允许我注册一个新用户。注册请求来自单独的HTML页面,其中包含标准注册表单。
鉴于我见过的帖子标题示例都是一样的:
app.post('/', function (req, res)
如何区分请求?
我的代码:
var express = require('express');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '12345678',
database: 'project_eclipse',
port: 3306
});
connection.connect(function (err) {
if (!err) {
console.log("Database is connected ... \n\n");
} else {
console.log("Error connecting database ... \n\n");
}
});
var app = express();
// instruct the app to use the `bodyParser()` middleware for all routes
app.use(bodyParser());
app.use(express.static(__dirname + '/public'));
app.post('/', function (request, response) {
console.log('searching for user: ', request.body.usr);
//console.log(request.body.pass);
var usr = request.body.usr;
var pass = request.body.pass;
connection.query('SELECT * FROM eclipse_users WHERE username=? AND password = md5(?)', [usr, pass], function (err, rows, fields) {
if (!err) {
//console.log('The solution is: ', rows);
var n_rows = rows.length;
console.log('number of rows returned: ', n_rows);
if (n_rows == 1) response.json({
msg: 'user exists'
});
else response.json({
msg: 'user does not exist'
});
} else {
console.log('Error while performing Query.');
connection.end();
}
});
});
app.listen(80, "127.0.0.1");
console.log('Server running at http://127.0.0.1:80/');
答案 0 :(得分:2)
变体1,另一个网址:
app.post('/registration', function (req, res) {
// ...
});
变体2,参数动作:
app.post('/:action', function (req, res) {
if (req.param('action') === 'registration') {
// ...
}
});
变式3,通过帖子采取行动:
app.post('/', function (req, res) {
if (req.param('action') === 'registration') {
// ...
}
});
答案 1 :(得分:1)
一种方法是:
app.post('/:register', function(request, response){
console.log('registering user: ',request.body.usr);
}
在调用帖子时传递注册标志。
但是,如果您使用app.get:
,那么检查用户有效性的代码会更好app.get('/', function(...)) {...}
这样你就可以拥有一个没有注册部分的注册变量的app.post。