Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions client/src/componets/Blogs.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,20 @@ import config from "../config";
const Blogs = () => {
const [blogs, setBlogs] = useState();
const sendRequest = async () => {
const res = await axios
.get(`${config.BASE_URL}/api/blogs`)
.catch((err) => console.log(err));
const data = await res.data;
let res;
try {
res = await axios.get(`${config.BASE_URL}/api/blogs`);
} catch (err) {
console.log(err);
throw err; // Re-throw the error to be caught by the .then().catch() chain
}
const data = res.data;
return data;
};
useEffect(() => {
sendRequest().then((data) => setBlogs(data.blogs));
sendRequest()
.then((data) => setBlogs(data.blogs))
.catch((err) => console.log("Fetch blogs error:", err)); // Add catch block
}, []);
console.log(blogs);
return (
Expand Down
25 changes: 15 additions & 10 deletions client/src/componets/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,33 +30,38 @@ const Login = () => {
const sendRequest = async (type = "login") => {
console.log("inside send req");
console.log(`${config.BASE_URL}/api/users/${type}`);
const res = await axios
.post(`${config.BASE_URL}/api/users/${type}`, {
let res;
try {
res = await axios.post(`${config.BASE_URL}/api/users/${type}`, {
name: inputs.name,
email: inputs.email,
password: inputs.password,
})
.catch((err) => console.log(err));
});
} catch (err) {
console.log(err);
throw err; // Re-throw the error to be caught by the .then().catch() chain
}

const data = await res.data;
const data = res.data;
console.log("return");
console.log(data);
return data;
};

const handleSubmit = (e) => {
e.preventDefault();
console.log(inputs);
if (isSignup) {
sendRequest("signup")
.then((data) => localStorage.setItem("userId", data.user._id))
.then((data) => localStorage.setItem("userId", data.data.user._id))
.then(() => dispath(authActions.login()))
.then(() => naviagte("/blogs"));
.then(() => naviagte("/blogs"))
.catch((err) => console.log("Signup error:", err)); // Add catch block
} else {
sendRequest()
.then((data) => localStorage.setItem("userId", data.user._id))
.then((data) => localStorage.setItem("userId", data.data.user._id))
.then(() => dispath(authActions.login()))
.then(() => naviagte("/blogs"));
.then(() => naviagte("/blogs"))
.catch((err) => console.log("Login error:", err)); // Add catch block
}
};
return (
Expand Down
1 change: 1 addition & 0 deletions server/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
MONGO_URI = mongodb://localhost:27017/BlogApp
1 change: 0 additions & 1 deletion server/.env.example

This file was deleted.

102 changes: 59 additions & 43 deletions server/controller/user-contoller.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,62 +4,78 @@ const { ApiResponse } = require("../utils/ApiResponse");
const { ApiError } = require("../utils/ApiError");

const getAllUser = async (req, res, next) => {
try {
const users = await User.find();
if (!users || users.length === 0) {
return res.status(404).json(new ApiError(404, "Users not found"));
}
return res.status(200).json(new ApiResponse(200, { users }, "Users fetched successfully"));
} catch (err) {
console.error(err);
return res.status(500).json(new ApiError(500, "Server error while fetching users"));
try {
const users = await User.find();
if (!users || users.length === 0) {
return res.status(404).json(new ApiError(404, "Users not found"));
}
return res
.status(200)
.json(new ApiResponse(200, { users }, "Users fetched successfully"));
} catch (err) {
console.error(err);
return res
.status(500)
.json(new ApiError(500, "Server error while fetching users"));
}
};

const signUp = async (req, res, next) => {
const { name, email, password } = req.body;

const { name, email, password } = req.body;

try {
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json(new ApiError(400, "User already exists"));
}
try {
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json(new ApiError(400, "User already exists"));
}

const hashedPassword = bcrypt.hashSync(password, 10);
const user = new User({
name,
email,
password: hashedPassword,
blogs: []
});
const hashedPassword = bcrypt.hashSync(password, 10);
const user = new User({
name,
email,
password: hashedPassword,
blogs: [],
});

await user.save();
return res.status(201).json(new ApiResponse(201, { user }, "User registered successfully"));
} catch (e) {
console.error(e);
return res.status(500).json(new ApiError(500, "Server error while signing up"));
}
await user.save();
return res
.status(201)
.json(new ApiResponse(201, { user }, "User registered successfully"));
} catch (e) {
console.error(e);
return res
.status(500)
.json(new ApiError(500, "Server error while signing up"));
}
};

const logIn = async (req, res, next) => {
const { email, password } = req.body;

try {
const existingUser = await User.findOne({ email });
if (!existingUser) {
return res.status(404).json(new ApiError(404, "User not found"));
}
const { email, password } = req.body;

const isPasswordCorrect = bcrypt.compareSync(password, existingUser.password);
if (!isPasswordCorrect) {
return res.status(400).json(new ApiError(400, "Incorrect Password"));
}
try {
const existingUser = await User.findOne({ email });
if (!existingUser) {
return res.status(404).json(new ApiError(404, "User not found"));
}

return res.status(200).json(new ApiResponse(200, { user: existingUser }, "Login successful"));
} catch (err) {
console.error(err);
return res.status(500).json(new ApiError(500, "Server error while logging in"));
const isPasswordCorrect = bcrypt.compareSync(
password,
existingUser.password,
);
if (!isPasswordCorrect) {
return res.status(400).json(new ApiError(400, "Incorrect Password"));
}

return res
.status(200)
.json(new ApiResponse(200, { user: existingUser }, "Login successful"));
} catch (err) {
console.error(err);
return res
.status(500)
.json(new ApiError(500, "Server error while logging in"));
}
};

module.exports = { getAllUser, signUp, logIn };
106 changes: 23 additions & 83 deletions server/package.json
Original file line number Diff line number Diff line change
@@ -1,83 +1,23 @@
{


"name": "blogapp",


"version": "1.0.0",


"description": "",


"main": "server.js",


"scripts": {




"start": "nodemon server.js",




"test": "echo \"Error: no test specified\" && exit 1"


},


"author": "khushi patel",


"license": "ISC",


"devDependencies": {




"nodemon": "^2.0.16"


},


"dependencies": {




"bcryptjs": "^2.4.3",




"cors": "^2.8.5",




"dotenv": "^16.5.0",




"express": "^4.18.1",




"helmet": "^8.1.0",




"mongoose": "^6.3.4"


}
}
{
"name": "blogapp",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "nodemon server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "khushi patel",
"license": "ISC",
"devDependencies": {
"nodemon": "^2.0.16"
},
"dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^16.5.0",
"express": "^4.18.1",
"helmet": "^8.1.0",
"mongoose": "^6.3.4"
}
}
10 changes: 10 additions & 0 deletions server/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1213,6 +1213,11 @@ fresh@0.5.2:
resolved "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz"
integrity sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==

fsevents@~2.3.2:
version "2.3.3"
resolved "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz"
integrity sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==

function-bind@^1.1.2:
version "1.1.2"
resolved "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz"
Expand Down Expand Up @@ -1272,6 +1277,11 @@ hasown@^2.0.0:
dependencies:
function-bind "^1.1.2"

helmet@^8.1.0:
version "8.2.0"
resolved "https://registry.npmjs.org/helmet/-/helmet-8.2.0.tgz"
integrity sha512-DRgTIUgnWcJ62KyarxxziuqYxKGnR6Rgg19BlbucN/dpmJbl1XOit6qvoOX0ZT+HhWe5OUVhU/a1zpGyc1xA0Q==

http-errors@2.0.0:
version "2.0.0"
resolved "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz"
Expand Down