gpt4 book ai didi

node.js - NodeJS - req.params 未定义

转载 作者:太空宇宙 更新时间:2023-11-03 23:02:05 24 4
gpt4 key购买 nike

我需要通过 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 是一个数字。然后我将其发送到我的服务器,但是当我想查看获取的参数时,出现错误:
未定义

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

最佳答案

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

正确签名:

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

关于node.js - NodeJS - req.params 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45167047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com