here is the error:
POST http://localhost:8000/signup 500 (Internal Server Error) api.js:146
Promise.then(async)
(anonymous) api.js:143
API.\<computed\> api.js:142
signupUser SignInUpPage.jsx:113
onClick SignInUpPage.jsx:279
here is my api.js file
import axios from "axios";
import {
API_NOTIFICATION_MESSAGES,
SERVICE_URLS,
} from "../constants/config.js";
//make single api with api interseptors
const API_URL = "http://localhost:8000";
const axiosInstance = axios.create(
//make api and save it in an instance
{
baseURL: API_URL,
timeout: 10000, //if delayed and api goes in pending then timeout
headers: {
"Content-Type": "application/json",
},
}
);
axiosInstance.interceptors.request.use(
//intercept request
function (config) {
//first callback fun. in case of successful
return config;
},
function (error) {
//second callback fun. in case of error
return Promise.reject(error);
}
);
//at the strat pf api loader is shown
axiosInstance.interceptors.response.use(
//intercept response
function (response) {
//Stop global loader here
return processResponse(response);
},
function (error) {
//Stop global loader here
return Promise.reject(processError(error));
}
);
// -------------------------------------------------------------------
// if success -> return {isSuccess: true, data: object} //200 around 202, 204
// if error -> return {isFailure: true, status: string, msg: string, code: int}
//--------------------------------------------------------------------
const processResponse = (response) => {
if (response?.status === 200) {
return { isSuccess: true, data: response.data };
} else {
return {
isFailure: true,
status: response?.status,
msg: response?.msg,
code: response?.code,
};
}
};
// -------------------------------------------------------------------
// if success -> return {isSuccess: true, data: object} //200 around 202, 204
// if error -> return {isFailure: true, status: string, msg: string, code: int}
//--------------------------------------------------------------------
const processError = (error) => {
if (error.response) {
//if get response in error
//request made successfully but server responded with status code other than 200
//i.e. that falls out of the range of 2.x.x range
// console.log("ERROR IN RESPONSE:", error.toJSON());
console.log("ERROR IN RESPONSE:", error.response);
return {
isError: true,
msg: API_NOTIFICATION_MESSAGES.responseFailure,
code: error.response.status, //error code from backend
};
} else if (error.request) {
//if get request in error
//request made successfully but no response was received from the server
// console.log("ERROR IN REQUSET:", error.toJSON());
console.log("ERROR IN REQUSET:", error.request);
return {
isError: true,
msg: API_NOTIFICATION_MESSAGES.requestFailure,
code: "",
};
} else {
//if gets nothing in error
//something happened in setting up request that triggers an erro
//i.e. some problem in frontend
// console.log("ERROR IN NETWORK:", error.toJSON());
console.log("ERROR IN RESPONSE:", error);
return {
isError: true,
msg: API_NOTIFICATION_MESSAGES.networkError,
code: "",
};
}
};
const API = {};
for (const [key, value] of Object.entries(SERVICE_URLS)) {
API[key] = (body, showUploadProgress, showDownloadProgress) => {
return new Promise((resolve, reject) => {
axiosInstance({
method: value.method,
url: value.url,
data: body,
responseType: value.responseType,
onUploadProgress: function (progress) {
if (showUploadProgress) {
let percentageCompleted = Math.round(
(progress.loaded * 100) / progress.total
);
showUploadProgress(percentageCompleted);
}
},
onDownloadProgress: function (progress) {
if (showDownloadProgress) {
let percentageCompleted = Math.round(
(progress.loaded * 100) / progress.total
);
showDownloadProgress(percentageCompleted);
}
},
validateStatus: (status) => {
return true; // I'm always returning true, you may want to do it depending on the status received
},
})
.then((response) => {
resolve(processResponse(response));
})
.catch((error) => {
reject(processError(error));
});
});
};
}
export { API };
here is my SignInUpPage.jsx
import React, { useState } from "react";
import {
Box,
TextField,
Button,
styled,
Typography,
FormControl,
InputLabel,
Input,
InputAdornment,
IconButton,
} from "@mui/material";
import Visibility from "@mui/icons-material/Visibility";
import VisibilityOff from "@mui/icons-material/VisibilityOff";
import logo_image from "./../../assets/images/secondary.png";
import PersonIcon from "@mui/icons-material/Person";
import VpnKeySharpIcon from "@mui/icons-material/VpnKeySharp";
import "./../../styles/sign-in-up-page.css";
import EmailSharpIcon from "@mui/icons-material/EmailSharp";
import { API } from "./../../service/api.js";
//Styled Tags
const StyledBox = styled(Box)`
width: 400px;
margin: auto;
box-shadow: 5px 2px 5px 2px rgba(0, 0, 0, 0.2);
border-radius: 7px;
`;
const StyledImage = styled("img")({
width: 200,
margin: "0 auto 30px",
display: "flex",
padding: "50px 0 0",
});
// or give margin like ...
// const StyledImage = styled("img")({
// width: 200,
// margin: "30px auto",
// display: "flex",
// padding: "50px 0 0",
// });
const Wrapper = styled(Box)`
padding: 25px 35px;
display: flex;
flex: 1;
flex-direction: column;
& > div,
& > button,
& > p {
margin-top: 20px;
}
`;
const StyledButton = styled(Button)`
text-transform: none;
background: rgba(138, 154, 91, 1);
color: white;
border-radius: 7px;
`;
const StyledOtherButton = styled(Button)`
text-transform: none;
background: #fff;
color: #2874f0;
height: 20px;
border-radius: 7px;
box-shadow: none;
`;
const Error = styled(Typography)`
font-size: 10px;
color: #ff6161;
line-height: 0;
margin-top: 10px;
font-weight: 600;
`;
const signupInitialValues = {
email: "",
fullname: "",
password: "",
};
export default function SignInUpPage() {
const [showPassword, setShowPassword] = React.useState(false);
const handleClickShowPassword = () => setShowPassword((show) => !show);
const handleMouseDownPassword = (event) => {
event.preventDefault();
};
const [account, toggleAccount] = React.useState("signin");
const [signup, setSignup] = useState(signupInitialValues);
const [error, setError] = useState("");
const toggleSignup = () => {
account === "signup" ? toggleAccount("signin") : toggleAccount("signup");
};
const onInputChange = (e) => {
// setSignup({ ...signup, [e.target.fullname]: e.target.value }); //fullname is key for signup object and .value corresponds to the value of the object
const { name, value } = e.target;
setSignup({ ...signup, [name]: value });
};
const signupUser = async () => {
let response = await API.userSignup(signup);
if (response.isSuccess) {
setError("");
setSignup(signupInitialValues);
toggleAccount("signin");
} else {
setError("Something went wrong! Please try again later.");
}
};
return (
<>
<StyledImage src={logo_image} alt="Secondary Logo" />
<StyledBox>
<Box>
{account === "signin" ? (
<Wrapper>
<Box sx={{ display: "flex", alignItems: "flex-end" }}>
<PersonIcon
sx={{ color: "action.active", mr: 1, my: 0.5 }}
></PersonIcon>
<TextField
id="username-textfield"
label="Your Username or Email"
variant="standard"
sx={{ width: "100%" }}
></TextField>
</Box>
<Box sx={{ display: "flex", alignItems: "flex-end" }}>
<VpnKeySharpIcon
sx={{ color: "action.active", mr: 1, my: 0.5 }}
></VpnKeySharpIcon>
<FormControl
sx={{ m: 0 }}
variant="standard"
style={{ width: "100%" }}
>
<InputLabel htmlFor="standard-adornment-password">
Your Password
</InputLabel>
<Input
id="standard-adornment-password"
type={showPassword ? "text" : "password"}
endAdornment={
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={handleClickShowPassword}
onMouseDown={handleMouseDownPassword}
>
{showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
}
/>
</FormControl>
</Box>
<StyledButton variant="contained" style={{ width: "100%" }}>
Sign in
</StyledButton>
{error && <Error>{error}</Error>}
<Box
sx={{ display: "flex", alignItems: "flex-end", margin: "auto" }}
>
<Typography
style={{
color: "grey",
textAlign: "center",
fontSize: "14px",
}}
>
New to InkOdy?
</Typography>
<StyledOtherButton
variant="text"
onClick={() => toggleSignup()}
>
Sign Up
</StyledOtherButton>
</Box>
</Wrapper>
) : (
<Wrapper>
<Box sx={{ display: "flex", alignItems: "flex-end" }}>
<PersonIcon
sx={{ color: "action.active", mr: 1, my: 0.5 }}
></PersonIcon>
<TextField
id="signup-fullname-textfield"
label="Your Firstname & Lastname"
variant="standard"
// InputProps={{
// endAdornment: (
// <InputAdornment position="end">
// <PersonIcon />
// </InputAdornment>
// ),
// }}
sx={{ width: "100%" }}
onChange={(e) => onInputChange(e)}
name="fullname"
// size="small"
></TextField>
</Box>
<Box sx={{ display: "flex", alignItems: "flex-end" }}>
<EmailSharpIcon
sx={{ color: "action.active", mr: 1, my: 0.5 }}
></EmailSharpIcon>
<TextField
id="email-textfield"
label="Enter your Email"
variant="standard"
// InputProps={{
// endAdornment: (
// <InputAdornment position="end">
// <PersonIcon />
// </InputAdornment>
// ),
// }}
style={{ width: "100%" }}
onChange={(e) => onInputChange(e)}
name="email"
// size="small"
></TextField>
</Box>
<Box sx={{ display: "flex", alignItems: "flex-end" }}>
<VpnKeySharpIcon
sx={{ color: "action.active", mr: 1, my: 0.5 }}
></VpnKeySharpIcon>
<FormControl
style={{ width: "100%" }}
sx={{ m: 0 }}
variant="standard"
onChange={(e) => onInputChange(e)}
name="password"
>
<InputLabel htmlFor="standard-adornment-password">
Set Password
</InputLabel>
<Input
id="standard-adornment-password"
type={showPassword ? "text" : "password"}
endAdornment={
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={handleClickShowPassword}
onMouseDown={handleMouseDownPassword}
>
{showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
}
/>
</FormControl>
</Box>
<StyledButton
variant="contained"
style={{ width: "100%" }}
onClick={() => signupUser()}
>
Sign Up
</StyledButton>
{error && <Error>{error}</Error>}
<Box
sx={{ display: "flex", alignItems: "flex-end", margin: "auto" }}
>
<Typography
style={{
color: "grey",
textAlign: "center",
fontSize: "14px",
}}
>
Already have an account?
</Typography>
<StyledOtherButton
variant="text"
onClick={() => toggleSignup()}
>
Sign In
</StyledOtherButton>
</Box>
</Wrapper>
)}
</Box>
</StyledBox>
</>
);
}
here is my app.js
import express from "express";
import dotenv from "dotenv";
import cors from "cors";
import bodyParser from "body-parser";
//import connction to database
import Connection from "./database/db.js";
//import routes
import router from "./routes/route.js";
dotenv.config();
const app = express();
app.use(cors());
app.use(bodyParser.json({ extended: true })); //we use the body parser because when we add invalid characters in URL like space the parser replaces it with some characters like 9%0%%
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/", router);
app.get("/", (req, res) => {
res.send("Hello World!");
});
const PORT = 8000;
app.listen(PORT, () =>
console.log(`Server is running successfully on Port ${PORT}`)
);
const USERNAME = process.env.DB_USERNAME;
const PASSWORD = process.env.DB_PASSWORD;
Connection(USERNAME, PASSWORD);
//userController.js
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';
import Token from './../models/Token.js';
import User from './../models/User.js';
dotenv.config();
export const signupUser = async (request, response) => {
try {
// const salt = await bcrypt.genSalt();
// const hashedPass
word = await bcrypt.hash(request.body.password, salt);
const hashedPassword = await bcrypt.hash(request.body.password, 10);
const user = { email: request.body.email, fullname: request.body.fullname, password: hashedPassword }
// const {email, fullname, password} = request.body;
const newUser = new User(user);
await newUser.save();
// response.send(newUser);
return response.status(200).json({ msg: 'Signup successfull' });
} catch (error) {
return response.status(500).json({ msg: 'Error while signing up user' });
}
}
export const signinUser = async (request, response) => {
let user = await User.findOne({ username: request.body.username });
if (!user) {
return response.status(400).json({ msg: 'Username does not match' });
}
try {
let match = await bcrypt.compare(request.body.password, user.password);
if (match) {
const accessToken = jwt.sign(user.toJSON(), process.env.ACCESS_SECRET_KEY, { expiresIn: '15m'});
const refreshToken = jwt.sign(user.toJSON(), process.env.REFRESH_SECRET_KEY);
const newToken = new Token({ token: refreshToken });
await newToken.save();
response.status(200).json({ accessToken: accessToken, refreshToken: refreshToken,name: user.name, username: user.username });
} else {
response.status(400).json({ msg: 'Password does not match' })
}
} catch (error) {
response.status(500).json({ msg: 'error while login the user' })
}
}
export const signoutUser = async (request, response) => {
const token = request.body.token;
await Token.deleteOne({ token: token });
response.status(204).json({ msg: 'logout successfull' });
}
i think the problem might lie in backend cuz there is error showing cannot GET/ on localhaost:8000 but i am exactly not able to find the origin of the problem.
also there occurs error while verifying server side using POSTMAN