I don't know what have bellow error:
TypeError: res.json is not a function
I readed express documentation, and don't see any wrong syntax or other errrors.
Code:
- index.js
import express from "express";
import postRoutes from "./routes/posts.js";
const app = express();
app.use(express.json());
app.use("/api/posts", postRoutes);
app.listen(8800, () => {
console.log("Server is running on port 8800");
});
- ./routes/posts.js
import express from "express";
const router = express.Router();
router.get("/", (res, req) => {
res.json("This works!");
});
export default router;
CodePudding user response:
Because the request object indeed has no json()
function.
You mixed up the parameter names and called the request object res
and the response object req
. Swap them to make it less confusing:
router.get("/", (req, res) => {
res.json("This works!");
});
CodePudding user response:
edit:
router.get("/", (res, req) => {
res.json("This works!");
});
to
router.get("/", (req, res) => {
res.json("This works!");
});
the (res, req) has to be in a specific order
CodePudding user response:
The arguments in router.get are wrong. Its (req, res)
now (res, req)
This is how it should look like:
router.get("/", (req, res) => {
res.json("This works!");
});
CodePudding user response:
The first argument to the Handler
is always request
and the second is response
often written in short from req
and res
. So change your code to this. More on this in this routing documentation
router.get("/", (req, res) => {
res.json("This works!");
});
Note: Your code will also work if you change your
res.json()
toreq.json()
since you have switched the conventional names. But doing this is confusing and I will not recommend doing it.