如何定义路线?

时间:2019-05-23 07:28:48

标签: node.js express

我是NodeJs和Express的新手。我想从Ajax文件进行ejs调用:

<script>
  $(document).ready(function() {
    $.ajax({
      async : false,
      url: "/organisation/list",
      success : function(data, status, xhr) {
        alert("finsihed");
      }
    });
  });
</script>

这是我的应用程序的配置:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');

var app = express();

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

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// 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');
});

module.exports = app;

这是index.js文件:

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

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

如何使到达Ajax网址/organisation/list成为可能?我应该在routes目录中创建另一个文件吗?

1 个答案:

答案 0 :(得分:1)

您可以简单地编写如下路线:

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

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});


/* GET organisation list. */
router.get('/organisation/list', function(req, res, next) {
      res.render('index', { title: 'Express' });
    });


module.exports = router;

,也可以创建一个单独的文件来处理与组织相关的所有请求。

  

app.js

app.use('/organization', require('./routes/organization.js');
  

routes / organization.js

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

/* GET home page. */
router.get('/list', function(req, res, next) {
  //res.render('index', { title: 'Express' });
  res.status(200).json([]);
});

module.exports = router;