I am trying to create a register form using React on the frontend, and Express with MongoDB atlas on the backend using typescript everywhere. When I click the submit button, nothing happens, but when I post the request using Postman application I get the following output after a long delay:
"Error occured while trying to proxy to: localhost:3000/api/[email protected]&password=test123"
And I get an empty record in my database, something like that:
_id: Object("5d7679d8fa74d54ebb0534b9")
__v: 0
Also after long delay i see this error in terminal in vscode:
[HPM] Error occurred while trying to proxy request /api/[email protected]&password=test123 from localhost:3000 to http://localhost:5000/ (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)
I created React frontend using "create-react-app", and already did the following instructions in post: When specified, "proxy" in package.json must be a string .
The thing is that I also have a contact form that is working and a proxy is working there, and I get the email when clicking submit in a contact form.
I show my package.json in my main folder (which I use to run my frontend and backend concurrently) in which I have two folders: backend (in which I have dist folder to which I transpile my .ts files to .js), and frontend folder.
{
"name": "ecommerce-template-mern",
"version": "1.0.0",
"main": "main.js",
"license": "MIT",
"scripts": {
"build": "tsc -p backend/.",
"backend": "nodemon backend/dist/main.js",
"frontend": "cd frontend && npm run start",
"dev": "concurrently --kill-others-on-fail \"npm run backend\" \"npm run frontend\""
},
"devDependencies": {
"concurrently": "^4.1.2",
"nodemon": "^1.19.2",
"tsc-watch": "^3.0.0"
},
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"http-proxy-middleware": "^0.20.0",
"nodemailer": "^6.3.0",
"typescript": "^3.6.2"
}
}
And package.json in frontend folder in which I have a proxy.
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:5000",
"dependencies": {
"@material-ui/core": "^4.4.0",
"@material-ui/icons": "^4.2.1",
"@types/jest": "24.0.18",
"@types/node": "^12.7.2",
"@types/react": "^16.9.2",
"@types/react-dom": "^16.9.0",
"axios": "^0.19.0",
"formik": "^1.5.8",
"http-proxy-middleware": "^0.20.0",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-router-dom": "^5.0.1",
"react-scripts": "3.1.1",
"styled-components": "^4.3.2",
"typescript": "3.5.3",
"yup": "^0.27.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@types/enzyme": "^3.10.3",
"@types/react-router": "^5.0.3",
"@types/react-router-dom": "^4.3.5",
"@types/reactstrap": "^8.0.4",
"@types/styled-components": "^4.1.18",
"@types/yup": "^0.26.23",
"bootstrap": "^4.3.1",
"enzyme": "^3.10.0",
"nodemon": "^1.19.1",
"react-addons-test-utils": "^15.6.2",
"react-bootstrap": "^1.0.0-beta.12",
"reactstrap": "^8.0.1",
"ts-node": "^8.3.0",
"ts-node-dev": "^1.0.0-pre.42"
}
}
Below is my code that should put data in my MongoDB atlas:
import express, { Application, Request, Response } from "express";
import bodyParser from "body-parser";
import * as dotenv from "dotenv";
dotenv.config({ path: __dirname + "/../.env" });
const app: Application = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const dbURI: any = process.env.MONGO_CONNECTION;
mongoose
.connect(dbURI, {
useNewUrlParser: true
})
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
const Schema = mongoose.Schema;
const UserSchema = new Schema({ email: String, password: String });
interface IUser extends mongoose.Document {
email: string;
password: string;
}
const User = mongoose.model<IUser>("User", UserSchema);
app.post("/api/register", (req: Request, res: Response) => {
const newUser = new User({
email: req.body.email,
password: req.body.password
});
newUser.save().then(() => console.log("New user in database!"));
});
const PORT = 5000
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
Above code outputs "New user in database!", but as I wrote on top of post I get an error, and "empty" object in a database.
Also, another thing to note is that when I run this code below:
const newUser2 = new User({
email: "[email protected]",
password: "123"
});
newUser2.save().then(() => console.log("New user in database!"));
I get the desired data record in MongoDB.
I also attach my register form in React below (almost same contact form works when sending mail, so I don't think there is problem with it):
import axios from "axios";
import { Field, Form, FormikProps, withFormik } from "formik";
import React from "react";
import * as Yup from "yup";
interface FormValues {
email: string;
password: string;
}
interface MyFormProps {
initialEmail?: string;
initialPassword?: string;
}
class RegisterForm extends React.PureComponent<FormikProps<FormValues>> {
render() {
const { values, touched, errors, isSubmitting } = this.props;
return (
<Form>
<Field
type="email"
name="email"
placeholder="email"
value={values.email}
/>
{touched.email && errors.email && <div>{errors.email}</div>}
<Field
type="password"
name="password"
placeholder="password"
value={values.password}
/>
{touched.password && errors.password && <div>{errors.password}</div>}
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</Form>
);
}
}
const FormikRegisterForm = withFormik<MyFormProps, FormValues>({
mapPropsToValues: props => {
return {
email: props.initialEmail || "",
password: ""
};
},
validationSchema: Yup.object().shape({
login: Yup.string()
.email("email is not valid")
.required("email is required"),
password: Yup.string().required("password is required")
}),
handleSubmit(values) {
const { email, password } = values;
axios
.post("/api/register", {
email,
password
})
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
}
})(RegisterForm);
export default FormikRegisterForm;
What can I change to get the desired result it database after clicking submit button in register form? Thanks for help in advance.