[英]Nodejs - multiple post requests
I've created a small express server using Nodejs and I'm currently able to handle a single post request - to check if a user exists or not. 我使用Node.js创建了一个小型快递服务器,目前能够处理一个发布请求-检查用户是否存在。
I need to incorporate an additional post request, which would allow me to register a new user. 我需要合并一个额外的帖子请求,这将允许我注册一个新用户。 The registration request comes from a separate HTML page which includes a standard registration form.
注册请求来自包含标准注册表格的单独HTML页面。
Given that the post header examples I've seen are all the same: 鉴于我看到的帖子标题示例都是相同的:
app.post('/', function (req, res)
How I can distinguish between the requests? 如何区分请求?
My code: 我的代码:
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/');
Variant 1, another url: 变体1,另一个网址:
app.post('/registration', function (req, res) {
// ...
});
Variant 2, parameter action: 变体2,参数操作:
app.post('/:action', function (req, res) {
if (req.param('action') === 'registration') {
// ...
}
});
Variant 3, action through post: 变体3,通过发布进行操作:
app.post('/', function (req, res) {
if (req.param('action') === 'registration') {
// ...
}
});
One way to do this is: 一种方法是:
app.post('/:register', function(request, response){
console.log('registering user: ',request.body.usr);
}
And pass the register flag while calling the post. 并在发帖时传递注册标志。
However, your code to check the validity of the user is better off if you use app.get: 但是,如果使用app.get,则检查用户有效性的代码会更好:
app.get('/', function(...)) {...}
This way you can have an app.post without the register variable for the registration part. 这样,您可以拥有一个app.post,而没有注册部分的register变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.