post route is not working for user registeration - node.js

This is the code for my post route. I am using registerPost to post a new user to mongoDB data base. Have a User schema made. The code for my registerPost function doesn't seem to be running.
export const registerPost = async (req, res) => {
const {username, password} = req.body;
const newUser = new User({username, password});
try {
await newUser.save();
console.log(newUser);
res.status(201).json(newUser);
} catch (error) {
res.status(409).json({ message: error.message });
}
}
These are the routes. Am not able to get a the /auth to go through on form submit. No console log no anything. I am missing something but am not sure.
import express from 'express';
import { getPosts } from '../controllers/posts.js'
import { createPost, updatePost, deletePost, registerPost } from '../controllers/posts.js'
const router = express.Router();
router.get('/', getPosts);
router.post('/', createPost);
router.patch('/:id', updatePost);
router.delete('/:id', deletePost);
router.post('/auth', registerPost);
export default router;
This is the react form code for the register part.
import React, { useEffect, useState } from 'react';
import { TextField, Button, Typography, Paper } from '#material-ui/core';
import useStyles from './styles.css';
const Auth = () => {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const divStyle = {
backgroundColor: 'white',
};
return (
<div style = {divStyle}>
<form>
<h1>Registration</h1>
<TextField
name='username'
variant='outlined'
label='username'
fullWidth
onChange={(e) => {
setUsername( e.target.value)
}}
/>
<TextField
name='password'
variant='outlined'
label='password'
fullWidth
onChange={(e) => {
setPassword( e.target.value)
}}
/>
<Button variant="container" color="primary" size="large" type="submit" fullwidth>Register</Button>
</form>
</div>
);
}
export default Auth;
Api doc
import axios from 'axios';
const url = 'http://localhost:5000/posts';
export const fetchPosts = () => axios.get(url);
export const createPost = (newPost) => axios.post(url, newPost);
export const updatePost = (id, updatedPost) => axios.patch(`${url}/${id}`, updatedPost);
export const deletePost = (id) => axios.delete(`${url}/${id}`);
export const likePost = (id) => axios.patch(`${url}/${id}/likePost`);

Related

Redirects to wrong page when logging in

it redirects to an empty js file when logging in, not to the js file I wrote. Should I redirect in my database code?
////////////////
const client = require('../../db')
const express = require('express');
const app = express();
const cors = require("cors");
app.use(cors());
app.use(express.json()); //req.body
app.listen(2136, ()=>{
console.log("Sever is now listening at port 5000");
})
client.connect();
app.post("/login", async (req, res) => {
try {
const { email, password } = req.body;
const user = await client.query(
`SELECT * FROM users WHERE email=$1 AND password=$2`,
[email, password]
);
if (user.rows.length === 0) {
res.status(404).send("Kullanıcı adı veya şifre yanlış");
} else {
res.send("Kullanıcı adı veya şifre doğru");
}
}catch (err) {
response
.status(500)
.json({ message: "Error in invocation of API: /login" })
}
});
this is my database code.
///////////////////////
import {
BrowserRouter as Router,
Route
} from "react-router-dom";
import React, { useState } from 'react'
import Navbar from '../../common/Navbar/Navbar';
import AdminPage from './AdminPage';
const User = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [user, setUser] = useState([]);
const [error, setError] = useState('');
const onSubmitForm = async e => {
e.preventDefault();
try {
const response = await fetch(`http://localhost:2136/login`,{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
console.log(email,password)
console.log(response);
if ((response.status)===404) {
setError('Invalid email or password');
} else
{
window.location.replace(`/AdminPage`);
}
} catch (err) {
console.error(error);
setError('An error occurred. Please try again later.');
}
};
return (
<>
<Navbar/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"></link>
<div className="container text-center">
<h1 className="my-5">Search for the Dormitory You Want</h1>
<form className="d-flex" onSubmit={onSubmitForm}>
<input
type="text"
name="name"
placeholder="Enter email ..."
className="form-control"
value={email}
onChange={e => setEmail(e.target.value)}
/>
<input
type="text"
name="name"
placeholder="Enter password ..."
className="form-control"
value={password}
onChange={e => setPassword(e.target.value)}
/>
<button className="btn btn-success">Submit
</button>
</form>
</div>
</>
)
}
export default User
this is my login page. the page it redirects to is a blank page. i don't understand why.
///////////////
import React, { useState } from 'react'
import AdminNavbar from '../../common/Navbar/AdminNavbar';
const AdminPage = () => {
return (
<>
<AdminNavbar/>
</>
);
}
export default AdminPage
and this the page I want to redirect AdminPage.So what can i do?
///////////////////
The difference between assign() and replace():
replace() removes the current URL from the document history.
With replace() it is not possible to use "back" to navigate back to the original document.
You can use assign method instead of location method

User not showing in local storage

I was working on my first MERN project and was trying to use local storage with context API, but the data is not getting reflected in the local storage and no error is getting reflected either in the console.
When I log in as a user, the local storage still stays empty.
Below is my Context.js code
import { createContext, useEffect, useReducer, useState } from "react";
import Reducer from "./Reducer";
const INITIAL_STATE = {
user: JSON.parse(localStorage.getItem("user")) || null,
isFetching: false,
error: false,
};
export const Context = createContext(INITIAL_STATE);
export const ContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(Reducer, INITIAL_STATE);
const [user, setItems] = useState([]);
useEffect(() => {
localStorage.setItem('user', JSON.stringify(state.user));
}, [state.user]);
return (
<Context.Provider
value={{
user: state.user,
isFetching: state.isFetching,
error: state.error,
dispatch,
}}
>
{children}
</Context.Provider>
);
};
Below is my login.jsx code
import { Link } from "react-router-dom";
import "./login.css"
import { useContext, useRef } from "react";
import axios from "axios";
import { Context } from "../../../context/Context";
export default function Login() {
const userRef = useRef();
const passwordRef = useRef();
const { user, dispatch, isFetching } = useContext(Context);
const handleSubmit = async (e) => {
e.preventDefault();
dispatch({ type: "LOGIN_START" });
try {
const res = await axios.post("/auth/login", {
username: userRef.current.value,
password: passwordRef.current.value,
});
dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
} catch (err) {
dispatch({ type: "LOGIN_FAILURE" });
}
};
console.log(isFetching)
return (
<div className="login">
<span className="loginTitle">Login</span>
<form className="loginForm" onSubmit={handleSubmit}>
<label>Username</label>
<input className="loginInput" type="text" placeholder="Enter your username..." ref=
{userRef} />
<label>Password</label>
<input className="loginInput" type="password" placeholder="Enter your
password..."
ref={passwordRef} />
<button className="loginButton" type="submit">Login</button>
</form>
<button className="loginRegisterButton">
<Link className="link" to="/register">Register</Link>
</button>
</div>
);
}
I have tried googling it out for 2 hours straight, but am not able to get the mistake from which it is arising. Any help is highly appreciated!!
import { createContext, useEffect, useReducer, useState } from "react";
import Reducer from "./Reducer";
const INITIAL_STATE = {
user: JSON.parse(localStorage.getItem("user")) || null,
isFetching: false,
error: false,
};
export const Context = createContext(INITIAL_STATE);
export const ContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(Reducer, INITIAL_STATE);
const [user, setItems] = useState([]);
useEffect(() => {
console.log(state.user);
localStorage.setItem('user', JSON.stringify(state.user));
}, [state.user]);
return (
<Context.Provider
value={{
user: state.user,
isFetching: state.isFetching,
error: state.error,
dispatch,
}}
>
{children}
</Context.Provider>
);
};
I think you'd better check first if user data is in there.

CURRENT_USER null, TypeError: Cannot read properties of null

I am facing an issue my user is always showing null in the backend, I don't know why.
I am following an Udemy course my tutor is saying middleware is responsible for user identification. but the problem is I typed the same code as my tutor is typing but his codes are working fine mine not.
I am using Axios from the front end to make request.
This my controller ==>
export const currentUser = async (req, res) => {
try {
const user = await User.findById(req._id).select("-password").exec();
console.log("CURRENT_USER", user); return res.json({ ok: true });
} catch (err) {
console.log(err);
}
};
This is my middleware ==>
import { expressjwt } from "express-jwt";
export const requireSignIn = expressjwt({ getToken: (req, res) => req.cookies.token, secret: process.env.JWT_SECRET, algorithms: ["HS256"], }) ;
This my front end code where I have been making request ===>
import { useEffect, useState, useContext } from "react";
import axios from "axios";
import { useRouter } from "next/router";
import { SyncOutlined } from "#ant-design/icons";
import UserNav from "../nav/userNav";
import { Context } from "../../context";
const UserRoutes = ({ children }) => {
const { state: { user } } = useContext(Context);
// state
const [ok, setOk] = useState(false);
// router
const router = useRouter();
useEffect(() => {
fetchUser();
}, []);
const fetchUser = async () => {
try {
const { data } = await axios.get("/api/current-user");
console.log(data);
if (data.ok) setOk(true);
} catch (err) {
console.log(err);
setOk(false);
router.push("/login");
}
};
return (
<>
{!ok ? (
<SyncOutlined spin className="d-flex justify-content-center display-1 text-primary p-5" />
) : (
<div className="UserNavSec">
<div className="UserNavCol1">
<div className="UserNavCont"><UserNav/></div
</div>
<div className="UserNavCol2"> {children} </div
</div>
)}
</>
);
};
export default UserRoutes;

How to send the data to server in react?

Please help me to fix my issue.
I am building react project using material ui.
This is contact us part in my project.
I want to send email when visitor see this site then.
Backend is working well with postman. But when I use front end request, Backend don't receive any values.
This is my code(Front).
import { React, useState } from 'react';
import axios from 'axios';
// material
import { Button, Typography, TextField, Stack } from '#material-ui/core';
//
import { varFadeInUp, MotionInView } from '../../animate';
// ----------------------------------------------------------------------
export default function ContactForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [subject, setSubject] = useState('');
const [message, setMessage] = useState('');
const basicUrl = 'http://localhost:8080/';
const handleEmailSender = (e) => {
e.preventDefault();
const data = {
name,
email,
subject,
message
};
axios.post(basicUrl, data).then((res) => {
console.log(res);
});
};
const handleNameChange = (e) => {
setName(e.target.value);
};
const handleEmailChange = (e) => {
setEmail(e.target.value);
};
const handleSubjectChange = (e) => {
setSubject(e.target.value);
};
const handleMessageChange = (e) => {
setMessage(e.target.value);
};
return (
<Stack spacing={5}>
<MotionInView variants={varFadeInUp}>
<Typography variant="h3">
Feel free to contact us. <br />
We'll be glad to hear from you
</Typography>
</MotionInView>
<Stack spacing={3}>
<MotionInView variants={varFadeInUp}>
<TextField fullWidth label="Name" onChange={handleNameChange} />
</MotionInView>
<MotionInView variants={varFadeInUp}>
<TextField fullWidth label="Email" onChange={handleEmailChange} />
</MotionInView>
<MotionInView variants={varFadeInUp}>
<TextField fullWidth label="Subject" onChange={handleSubjectChange} />
</MotionInView>
<MotionInView variants={varFadeInUp}>
<TextField fullWidth label="Enter your message here." multiline rows={4} onChange={handleMessageChange} />
</MotionInView>
</Stack>
<MotionInView variants={varFadeInUp}>
<Button size="large" variant="contained" onClick={handleEmailSender}>
Submit Now
</Button>
</MotionInView>
</Stack>
);
}
This is my backend Code.
const express = require("express");
const cors = require("cors");
const app = express();
const nodemailer = require("nodemailer");
app.use(cors());
// This responds with "Hello World" on the homepage
app.post("/", function (req, res) {
response = {
name: req.query.name,
email: req.query.email,
subject: req.query.subject,
message: req.query.message,
};
console.log(response.name);
let mailTransporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: "xxxxxx",
pass: "xxxxxx",
},
});
let mailDetails = {
from: response.email,
to: "xxxxxxx",
subject: response.subscribe,
text: response.message,
};
mailTransporter.sendMail(mailDetails, function (err, data) {
if (err) {
console.log("Error Occurs");
} else {
console.log("Email sent successfully");
}
});
res.send();
});
// This responds a GET request for the homepage
// app.get("/", function (req, res) {
// console.log("Got a GET request for the homepage");
// res.send("Hello GET");
// });
app.listen(8080, function () {
console.log("Server is running at http://localhost:8080/");
});
Please help me please :-)
Try using req.body and have a look at this post on how to append form data: axios post request to send form data
app.post("/", function (req, res) {
console.log({req})
response = {
name: req.body.name,
email: req.body.email,
subject: req.body.subject,
message: req.body.message,
};

What's the right way to get data from ReactJS front-end to NodeJS back-end?

How to correctly orginize ReactJS code in that way, that click-handler from client send data to back-end (Current URL and input value in field "body") (Twilio module) ?
Front-end:
<form>
<input type="text"/>
<button onClick={handler}>Send</button>
</form>
Back-end:
const accountSid = "account-Sid";
const authToken = "auth-token";
const client = require("twilio")(accountSid, authToken);
const SendMessage = client.messages
.create({
body: "text_here",
from: "whatsapp:+#recipient",
to: "whatsapp:+#reciever",
})
.then((message) => console.log(message.sid))
.done();
module.exports = {
SendMessage,
};
Pseudo-code in front-end:
import SendMessage from "../server/messageAPI/messageAPI";
const location = useLocation();
let value = "";
const handler = () => {
SendMessage(location, value);
};
<form>
<input type="text" value={value} />
<button onClick={handler}>Send</button>
</form>;
You backend code -:
const accountSid = "account-Sid";
const authToken = "auth-token";
const client = require("twilio")(accountSid, authToken);
const theNumberYouBoughtFromTwilio = "123457696";
const SendMessage = (message, to) =>
client.messages
.create({
body: `${message}`,
from: `whatsapp:+${theNumberYouBoughtFromTwilio}`,
to: `whatsapp:+${to}`,
})
.then((message) => console.log(message.sid))
.done();
module.exports = {
SendMessage,
};
Your frontend code :-
import React, { useState } from "react";
import SendMessage from "../server/messageAPI/messageAPI";
const App = () => {
const [message, setMessage] = useState("");
const messageHandler = async (e) => {
e.preventDefault();
console.log(message);
await SendMessage(location, message); // incase sendmesssage is async call which makes sense
};
return (
<div>
<form>
<input onChange={(e) => setMessage(e.target.value)} value={message} />
<button onClick={messageHandler}>Send</button>
</form>
</div>
);
};
export default App;
I would do something like this
const SendMessageComponent = () => {
const location = useLocation()
const [message, setMessage] = useState("")
const handleMessage = (event) => setMessage(event.target.value)
const sendMessage = () => SendMessage(location, message)
return (
<>
<input type="text" value={message} onChange={handleMessage} />
<button onClick={sendMessage}>Send</button>
</>
)
}

Resources