node.js - 在 Express : userid not found 中使用 rest api

标签 node.js mongodb express mongoose request

灵感来自 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
连同这本书,我编写了应用程序/服务器/ Controller :

路线:

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

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

module.exports = router;
和 Controller 。此处我的 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
};

最佳答案

当然你会找不到用户标识,因为你误用了字符串文字。在你的 Controller 中,从这个改变:

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

为此:

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

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

现在您的应用应该可以正确发出请求。

关于node.js - 在 Express : userid not found 中使用 rest api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50029821/

相关文章:

mongodb - 将 mongodb 与 neo4j 集成,是否有任何 API 可以链接它们?

javascript - Express.js 4 路由与 router.route 不匹配

javascript - Socket IO - 如何让多个管理员用户访问多个 URL 上的多个私有(private)房间

node.js - 使用 pg-promise 进行嵌套查询对象映射

node.js - 使用 Nock 响应 API 测试失败, "Error : Nock : No match for request"

mongodb - 连接到 mongoHQ shell 的 JavaScript 执行失败

javascript - 如何在 Node.js 中获取 url 作为参数?

node.js - 为什么 req.cookies.session 未定义? Firebase + Node + Express

javascript - 如何从 HTTP 响应 header 字符串中提取参数?

mongodb - 存储数百万个日志文件 - 每年大约 25 TB