NodeJS - req.params未定义

时间:2017-07-18 12:37:53

标签: node.js angular

我需要从服务器获取id的数据 我写了Angular 2的服务:

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';

import { AppConfig } from '../appConfig';
import { JwtService } from './jwt.service';

@Injectable()
export class MemberService {

  constructor(
      private http: Http,
      private appConfig: AppConfig,
      private jwtService: JwtService) { }

  getMembersById(id: number) {
    const headers = new Headers();
    headers.append('Authorization', 'Token ' + this.jwtService.getToken());

    return this.http.get(this.appConfig.urlServer + '/members/' + id, { headers: headers })
        .map((res: Response) => res.json())
  }
}

我的服务器代码:

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const flash = require('connect-flash');
const expressSession = require('express-session');
const nconf = require('./config');
const tables = require('./create_tables');
const routes = require('./routes');
const passport = require('passport');
const app = express();

const port = nconf.get('port');
app.set('port', (process.env.PORT || port));

tables.create_tables();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extend: false
}));

app.use(morgan('dev'));
app.use(cors());

app.use(passport.initialize());
app.use(passport.session());
app.use(expressSession({
    secret: 'keyboard cat'
}));
app.use(flash());

require('./passport/passport')(passport);

app.use('/', routes);

app.listen(app.get('port'));

module.export = app;

我还创建了index.js来设置应用的路由:

const express = require('express');
const router = express();
const members = require('./members');

router.use('/members', members);

module.exports = router;

我在members.js

中制作了这个方法
const express = require('express');
const mysql = require('mysql');
const nconf = require('../config');
const connection = mysql.createConnection(nconf.get('db'));
const token = require('../middlewares/token');
const router = express();

router.get('/:id', token.required, getGroupsById);

module.exports = router;

function getGroupsById(res, req) {
  console.log(req.params);
}

Id是一个数字。然后我把它发送到我的服务器,但当我想看到有参数我有错误:
undefined

我无法理解我在哪里犯了错误。我在stackoverflow的答案中进行了调查,这对我解决问题没有帮助 也许,某个地方我犯了错误,现在我找不到了。
请帮助我任何人。

1 个答案:

答案 0 :(得分:3)

您错误地定义了getGroupsById的签名,它应该是(req, res)而不是(res, req)

正确签名:

function getGroupsById(req, res) {
   console.log(req.params);
}