我是RESTful API的新手,我的应用程序遇到了问题。我想设置HTTP GET方法从mysql中检索数据,我认为文件app.js已经连接到数据库(但我不太清楚路由器是如何工作的)。我知道我需要创建一个路由器,但我只是不知道如何做它像post和get等,我不知道我错过了什么。请帮忙!我感谢您的时间并做出回应!
=============================================== ========================== 我想我没有描述我的问题,让我改一下。
现在我有一个模特
@模型/ Users.js
我有路由器文件
@ routers / index.js& user.js`
(它们都是快递生成的默认文件)
我还有一个半设置文件(我不确定)
@ app.js
我的目标是在url中输入/ whatever中的任何内容都可以从http获得响应,例如json数据或来自数据库的任何内容。我知道我的文件中存在很多问题(也许所有这些都没有正确写入),我只是希望得到一个帮助,使其正确,以便我理解结构。谢谢你的帮助!
app.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 routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var mysql = require('mysql');
require('./models/Users');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 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('/', routes);
app.use('/users', users);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
/models/User.js
var mysql = require('mysql');
var connection = mysql.createConnection({
connectionLimit : 100,
host : 'localhost',
user : 'root',
password : '',
database : 'ajs02'
});
connection.connect();
connection.query('SELECT * from post', function(err, rows, fields) {
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
connection.end();
/routers/index.js
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/match', function(req, res) {
mysql.query('SELECT * FROM ' + req.params.table + ' ORDER BY id DESC LIMIT 20', req.params.id, function(err, rows, fields) {
var user = new User(req.postId);
res.send(user)
connection.release();
});
});
router.get('/hw', function(req, res) {
res.send('hello world');
});
module.exports = router;
答案 0 :(得分:4)
RESTful API的工作原理与数据库已支持的CRUD(创建,读取,更新,删除)操作相同。您只需要将这些SQL操作转换为RESTful(HTTP请求)动词,如GET,PUT,POST和DELETE。
考虑:
// a GET request = a database READ or (a.k.a SELECT)
app.get('/path', function(req, res) {
connection.query('SELECT * FROM ' + req.params.table + ' ORDER BY id DESC LIMIT 20', req.params.id, function(err, rows, fields) {
res.json('.. assume you translated your database response a javascript object .. ')
connection.release();
});
});
// a POST request = a database CREATE (a.k.a INSERT)
app.post('/path', function(req, res) {
connection.query('INSERT INTO ' + req.params.table + ' SOME OTHER PARTS OF YOUR SQL QUERY', req.params.id, function(err, rows, fields) {
res.json('.. assume you translated your database response a javascript object again .. ')
connection.release();
});
});
// a PUT request = a database UPDATE
app.put('/path', function(req, res) {
connection.query('UPDATE ' + req.params.id + ' SOME OTHER PARTS OF YOUR SQL QUERY', req.params.id, function(err, rows, fields) {
res.json('.. assume you translated your database response a javascript object yet again .. ')
connection.release();
});
});
// a DELETE request = a database DELETE
app.delete('/path', function(req, res) {
connection.query('DELETE FROM ' + req.params.table + ' SOME OTHER PARTS OF YOUR SQL QUERY', req.params.id, function(err, rows, fields) {
res.json('.. assume you translated your database response a javascript object once again .. ')
connection.release();
});
});
至于路线,请从Express Routing Guide开始。在基本级别,定义的路由(例如/path
)对应于请求URI:http://yourserver.com/path
)。它还分别支持通配符,命名参数和正则表达式,如:/path/:id
,/path/*
和/path/id_.*$
。