我是Express和Node JS的新手,我最近学习了如何编写用于Express的API,但是最后,我遇到了一些问题,经过几次尝试我还是无法解决。我无法在localhost:8080 / users上得到响应
src / routes / users.js
const { Router } = require("express");
const router = Router();
const getUsers = (req, res) =>
res.send(Object.values(req.context.models.users));
const getUser = (req, res) =>
res.send(req.context.models.users[req.params.userId]);
router.get("/users/", getUsers);
router.get("/users/:userId", getUser);
module.exports = router;
src / routes / index.js
const user = require("./user");
const message = require("./message");
module.exports = {
user,
message
};
src / index.js
const express = require("express");
const app = express();
// Custom Modules
const routes = require("./routes");
const models = require("./models");
// Application-Level Middleware Starts
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
req.context = {
models,
me: models.users[1]
};
console.log(req.context.models.users);
next();
});
// Used Routes
app.use("/users", routes.user);
app.use("/messages", routes.message);
// App Listning to HTTPS Module
app.listen(process.env.PORT);
答案 0 :(得分:1)
您需要在 users.js 中修复端点:
router.get("/", getUsers);
router.get("/:userId", getUser);
原因是由于 index.js 中的app.use("/users", routes.user);
设置了用户端点。如果您将/users/
留在 users.js 中,则它将是 localhost:8080 / users / users / 。相同的问题可能是 / messages 。