Reputation: 69
I am having trouble with express.json()
function. I have checked numerous topics regarding this here and on the net but to no avail.
Here is the my code:
app.use(morgan("dev"));
app.use(cors());
app.use(helmet());
app.use(express.json());
app.use(express.urlencoded());
app.use("/api/users", userRoutes);
app.use("/api/articles", articleRoutes);
What I did:
express.json()
is above the router.express.urlencoded()
wasn't there, due to my research I placed it there but yet nothing worked.package.json
file.Here is my userController
code:
exports.create = (req, res) => {
try {
const { name } = req.body;
console.log(name);
const user = {
name,
};
res.json({
message: user,
text: "Is this working?",
});
} catch (error) {
console.log(error);
}
On Postman, here is what was returned:
{
"message": {},
"text": "Is this working?"
}
What should be the problem if express.json()
passes the data to Postman but yet res.body
returns undefined
?
Upvotes: 0
Views: 1943
Reputation: 502
How about change user to key value like :
exports.create = (req, res) => {
try {
const { name } = req.body;
console.log(name);
const user = {
name: name // add this one
};
res.json({
message: user,
text: "Is this working?",
});
} catch (error) {
console.log(error);
}
Upvotes: 0
Reputation: 8773
You need to add body-parser in your controler,
npm install body-parser
const bodyParser = require('body-parser')
app.use(morgan("dev"));
app.use(cors());
app.use(helmet());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }))
app.use("/api/users", userRoutes);
app.use("/api/articles", articleRoutes);
You can follow the steps here :
Upvotes: 1