node.js - 在 Express 中使用休息 api:未找到用户 ID
问题描述
灵感来自Gettin MEAN我正在制作自己的应用程序。我尝试在 Express 中将前端连接到后端。我复制了文本,但我的 console.log 仍然给我消息“找不到用户 ID”。我想我已经接近终点了。任何提示或有用的链接表示赞赏。
- 用户模型
const userSchema = new Schema({
firstName: String,
lastName: String,
userName: String,
telephone: String,
password: String
});
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;
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
};
解决方案
当然,您将找不到任何用户 ID,因为您误用了字符串文字。在您的控制器内部,从这里更改:
const path = '/api/users/${req.params.userid}';
对此:
const path = `/api/users/${req.params.userid}`;
字符串文字仅在使用反斜杠`时才有效。
现在您的应用程序应该正确地发出请求。
推荐阅读
- html - 为什么使用 *ngFor 后滑动器滑块不播放
- mysql - 通过 Laravel 存储 3rd 方数据库/API 凭证的安全方式
- laravel - 我想在 cakephp 框架中使用 laravel 密码哈希算法
- c++ - 这个函数期望从 std::istream 解析什么格式的输入?
- c# - 如何清除 ASP.NET Core 中的 MemoryCache?
- github - Markdown 文件的 YAML 标头在文档顶部生成奇数表
- java - 使用Java循环将字符串转换为单词中每个字母的数字unicode等价物?
- .net - Docker - Windows 容器 - 安装 DotNet 框架 472
- java - Firebase 身份验证成功后,如何进入 Android Studio 中的下一个活动?
- apache-spark - 无法使用火花流从 kafka 主题中读取数据