首页 > 解决方案 > 在 Express 中使用休息 api:未找到用户 ID

问题描述

灵感来自Gettin MEAN我正在制作自己的应用程序。我尝试在 Express 中将前端连接到后端。我复制了文本,但我的 console.log 仍然给我消息“找不到用户 ID”。我想我已经接近终点了。任何提示或有用的链接表示赞赏。

  1. 用户模型

const userSchema = new Schema({

    firstName: String,
    lastName: String,
    userName: String,
    telephone: String,
    password: String
    
});
2. api中的路由

router
    .route('/users/:userid')
    .get(ctrlUsers.userReadOne);
    
module.exports = router;

在 Postman 中,这个 get.request 有效(例如)

http://localhost:3000/api/users/5ad87da47bb05b0594fff5b6
我连同这本书一起编写了应用程序/服务器/控制器:

路线:

const express = require('express');
const router = express.Router();
const ctrlUsers = require('../controllers/users');

router.get('/users/:userid', ctrlUsers.userInfo);

module.exports = router;
和控制器。在这里,我的 console.log 给出了“找不到用户 ID”

const request = require('request');
const apiOptions = {
    server: 'http://localhost:3000'
};
if (process.env.NODE_ENV === 'production') {
    apiOptions.server = 'https://pure-temple-67771.herokuapp.com';
}



/*Get myprofile */
const userInfo = function (req, res) {
    const path = '/api/users/${req.params.userid}';
    requestOptions = {
        url: apiOptions.server + path,
        method: 'GET',
        json: {}
    };

    console.log('path  ' + requestOptions.url);

    request(
        requestOptions,
        (err, response, body) => {
            _rendermyProfile(req, res, body);
            console.log(body); // no userid found 
            });
};




const _rendermyProfile = function (req, res, userDetail) {
    res.render('myProfile', {
        profile: {
            title: 'Mijn profiel',
            firstName: userDetail.firstName,
            lastName: userDetail.lastName,
            email: userDetail.email,
            telephone: userDetail.telephone
        }
    });
};






module.exports = {
    userInfo
};

标签: node.jsmongodbexpressmongooserequest

解决方案


当然,您将找不到任何用户 ID,因为您误用了字符串文字。在您的控制器内部,从这里更改:

const path = '/api/users/${req.params.userid}';

对此:

const path = `/api/users/${req.params.userid}`;

字符串文字仅在使用反斜杠`时才有效。

现在您的应用程序应该正确地发出请求。


推荐阅读