【问题标题】:How to configure express router along with ES6?如何在 ES6 中配置 express 路由器?
【发布时间】:2016-02-14 05:33:27
【问题描述】:

我在 express 中有以下用于路由器文件的代码。

import express from 'express';
import  _  from 'lodash';
import { Devices, OwlElecMonitors } from '../models/';

var router = express.Router();

router.get('/api/devices/:id',function (req, res) {
    console.log(req);                   
    Devices.getDevicesByUserId({ userId: req.params.id },function(err, resp) {
        res.send(resp);
    });
});

export default router;

我正在尝试使用以下代码将其导入主文件

import api from './routes';
app.use('/api', api);

但代码返回 404 错误。我哪里错了?我需要进行哪些更改才能使其正常工作?

【问题讨论】:

  • 你是怎么运行这个的?即使使用 --harmony_modules 标志,我也无法让 ES6 模块工作。
  • 使用打字稿会帮助你

标签: node.js express routing ecmascript-6


【解决方案1】:

也可以通过跳过挂载参数来解决:

import api from './routes';
app.use(api);

【讨论】:

  • 这实际上对我有用。有趣的是,如果我提供 mount 参数 - 它会中断并返回“Cannot GET /foo”......为什么?
  • 啊,找到了: // 使用路由器和 401 任何通过 app.use('/admin', router, function (req, res) { res.sendStatus(401) }) 在:expressjs.com/en/guide/using-middleware.html
【解决方案2】:

您的 api 当前设置为 /api/api/devices/:id。 从路由器获取定义中删除/api

router                  
    .get('/devices/:id',function (req, res) { 

【讨论】:

  • 谢谢,这就是问题所在。
猜你喜欢
  • 2022-12-02
  • 2018-02-28
  • 1970-01-01
  • 2018-11-16
  • 2014-04-21
  • 2020-06-17
  • 2021-02-07
  • 1970-01-01
  • 2014-06-10
相关资源
最近更新 更多