Reputation: 843
I am building a REST API for my React application in using Express.js.
This is where I call the API from the frontend:
const signIn = async () => {
const user = await fetch(`${SERVER_URI}/users/signup`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email,
password,
}),
})
console.log(user);
};
On the API:
router.post("/users/signup", async (req, res) => {
try {
let user = new User({
name: req.body.name,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 10),
});
await user.save();
const token = await user.generateAuthToken();
if (!user) {
return res.status(400).send("User could not be created");
}
res.status(200).send({ user, token });
} catch (error) {
console.log(error);
res.status(500).send(error);
}
});
User gets created successfully in the database but when I log the response coming back from the API this is what I see in Chrome:
Response {type: "cors", url: "http://localhost:3002/users/signup", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:3002/users/signup"
[[Prototype]]: Response
I should be getting the new user object which has just been created along with the token.
What am I doing wrong here?
Upvotes: 0
Views: 155
Reputation: 96
The fetch
function returns a Response
object. You can use response.json()
get the object containing your returned data i.e { "user": ..., "token": ... }
.
Expected usage:
const signIn = async () => {
const response = await fetch(`${SERVER_URI}/users/signup`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email,
password,
}),
});
console.log(await response.json()); // { "user": ..., "token": ... };
};
Upvotes: 1