I'm trying to check a login form with passport js and I want that when the status is correct, to log the user in but when it is incorrect to return him to the login page. I've tried doing this with an if else statement but it is not working as I've tried to console log the status and it shows nothing.
This is my frontend:
import React, {useState} from 'react'
import './login.css'
import axios from 'axios'
import { useHistory } from "react-router-dom";
function Login() {
const [username, setUsername] = useState("")
const [password, setPassword] = useState("")
const [data, setData] = useState(null)
const history = useHistory()
const onChangeUsername = (e) => {
setUsername(e.target.value)
}
const onChangePassword = (e) => {
setPassword(e.target.value)
}
const onSubmit = (e) => {
e.preventDefault()
const users = {
username: username,
password: password
}
axios.post('http://localhost:4000/users/login', users)
.then(res => console.log(res.data))
}
const loginUser = () => {
axios.get("http://localhost:4000/users/login", {
withCredentials: true
}).then(res => {
if(res.status === 200) {
setData(res)
return history.push("/home")
}
else if(res.status === 400) {
return history.push("/login")
}
console.log(res.status)
})
}
return (
<div>
<img src="https://www.freepnglogos.com/uploads/twitter-logo-png/twitter-logo-vector-png-clipart-1.png" className="twitterlogo____image"/>
<h1 className="login_____headertext">Log in to Twitter</h1>
<div className="placeholder_____global">
<form onSubmit={onSubmit}>
<input className="placeholder____div" placeholder="Phone, email or username" onChange={onChangeUsername}/>
<div>
<input className="placeholder____div" placeholder="Password" type="password" onChange={onChangePassword}/>
</div>
<div>
<button className="twitter___loginbuttonpage" onClick={loginUser}>Log in</button>
</div>
</form>
<div className="forgetPassword_____div">
<p>Forgot password?</p>
<p>ยท</p>
<p>Sign up for Twitter</p>
</div>
</div>
</div>
)
}
export default Login
Server side code:
const express = require('express');
const router = express.Router();
const Users = require('../models/users.model.js')
const passport = require("passport")
require('../authentication/passportConfig.js')(passport)
router.route('/').get((req, res) => {
Users.find()
.then(users => res.json(users))
.catch(err => res.status(400).json('Error:' + err))
})
router.route('/login').post((req, res, next) => {
passport.authenticate("local" , (err, user, info) => {
if (err) throw err;
if (!user) res.status(400).send("No user exists");
else {
req.logIn(user, err => {
if (err) throw error;
res.status(200).send("Succesfully Authenticated")
})
}
})(req, res, next)
})
router.route('/login').get((req, res) => {
res.send(req.user)
})
router.route('/add').post(async(req,res) => {
const hashedPassword = await bcrypt.hash(req.body.password, 10)
const username = req.body.username
const password = hashedPassword
const email = req.body.email
const phone = req.body.phone
const monthOfBirth = req.body.monthOfBirth
const dayOfBirth = req.body.dayOfBirth
const yearOfBirth = req.body.yearOfBirth
const newUsers = new Users({
username,
password,
email,
phone,
monthOfBirth,
dayOfBirth,
yearOfBirth
})
newUsers.save()
.then (() => res.json("User Added"))
.catch(err => res.status(400).json('error' + err))
})
module.exports = router
Before reaching console you are returning the control in if else conditions.
move your console.log before if else.
const loginUser = () => {
axios.get("http://localhost:4000/users/login", {
withCredentials: true
}).then(res => {
console.log(res.status)
if(res.status === 200) {
setData(res)
return history.push("/home")
}
else if(res.status === 400) {
return history.push("/login")
}
})
}
Related
I solved the problem and should add an error message "Uncaught (in promise) SyntaxError: Unexpected end of JSON input"
When creating a new user, got the error 400
It was fine locally but doesn't work after deployed
**Note: The database in Heroku is different from Railway, there's no varchar in Railway, use text instead
I deployed react in Netlify and Express & Postgresql db in Railway
I doubted it was from the setUser part, but I have no clue what the problem is
Does it relate to useContext, cuz setUser is from there?
**Note: setUser is not the problem
// front-end sign up
import React, { useState, useContext } from "react";
import { useNavigate } from "react-router-dom";
import Button from "../Button";
import { Wrapper } from "./Signup.styles";
import { Context } from "../../context";
const Signup = () => {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState(false);
const [user, setUser] = useContext(Context);
const navigate = useNavigate();
const handleSubmit = () => {
if (!username || !password || !email) return setError(true);
try {
fetch("https://react-rmdb-backend-production.up.railway.app/signup", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
username: username,
email: email,
password: password
})
})
.then(res => res.json())
.then(user => {
if (user.id) {
setUser({
id: user.id,
username: user.username,
email: user.email
});
navigate("/");
}
});
} catch (error) {
setError(true);
}
};
const handleInput = e => {
const name = e.target.name;
const value = e.target.value;
if (name === "username") setUsername(value);
if (name === "password") setPassword(value);
if (name === "email") setEmail(value);
};
return (
<Wrapper>
{error && <div className="error">Oops! Something went wrong!</div>}
<h2>Sign Up</h2>
<label htmlFor="username">Username:</label>
<input
type="text"
value={username}
name="username"
onChange={handleInput}
/>
<label htmlFor="email">Email:</label>
<input type="email" value={email} name="email" onChange={handleInput} />
<label htmlFor="password">Password:</label>
<input
type="password"
value={password}
name="password"
onChange={handleInput}
/>
<Button text="Signup" callback={handleSubmit} />
</Wrapper>
);
};
export default Signup;
// back-end sign up
const handleSignup = (req, res, db, bcrypt) => {
const { username, email, password } = req.body;
if (!email || !username || !password) {
return res.status(400).json("Something went wrong");
}
const saltRounds = 10;
const hash = bcrypt.hashSync(password, saltRounds);
db.transaction((trx) => {
trx
.insert({
hash: hash,
email: email,
})
.into("login")
.returning("email")
.then((loginEmail) => {
return trx("users")
.returning("*")
.insert({
username: username,
email: loginEmail[0].email,
})
.then((user) => {
// should use res.json(user[0])
res.send(user[0]);
});
})
.then(trx.commit)
.catch(trx.rollback);
}).catch((err) => res.status(400).json("unable to sign up"));
};
module.exports = {
handleSignup,
};
Any advice would be appreciated.
I'm creating new app(e-commerce) using react and react-redux with axios. For back-end using Mongo-DB(MERN stack).
There is no problem when saving data to database, but when i get that data from database middleware can not reach token from headers. But postman work fine both get and save data.
I use the same middleware when saving data to database, it work fine. But when i try to fetch data from database i get unauthorized error.
here is my code.
FOR BACK-END;
Server file;
import express from "express";
import connectDB from "./config/db.js";
import dotenv from "dotenv";
import colors from "colors";
import productRoutes from "./routes/productRoutes.js";
import userRouters from "./routes/userRoutes.js";
import shippingAddressRoutes from "./routes/shippingAddressRoutes.js";
import { notFound, errorHandler } from "./middleware/errorMiddleware.js";
dotenv.config();
connectDB();
const app = express();
// body parser
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// API route
app.get("/", (req, res) => {
res.send("API is running....");
});
// route for products
app.use("/api/products", productRoutes);
// route for users
app.use("/api/users", userRouters);
// route for shipping address
app.use("/api/shippingaddress", shippingAddressRoutes);
app.use(notFound);
app.use(errorHandler);
const PORT = process.env.PORT || 5000;
app.listen(
PORT,
console.log(
`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold
)
);
shippingAddressRoute file;
import express from "express";
import {
saveAddress,
changeAddress,
getAddress,
} from "../controllers/shippingAddressController.js";
import protect from "../middleware/authMiddleware.js";
const router = express.Router();
router
.route("/")
.get(protect, getAddress)
.post(protect, saveAddress)
.put(protect, changeAddress);
export default router;
shippingAddressController file;
import asyncHandler from "express-async-handler";
import ShippingAddress from "../models/shippingAddressModel.js";
import User from "../models/userModel.js";
// #desc get address
// #route GET /api/shippingaddress
// #access Private
const getAddress = asyncHandler(async (req, res) => {
const user = User.findById(req.user._id);
if (user) {
const { email } = req.body;
const shippingAddress = await ShippingAddress.findOne({
userEmail: email,
});
if (shippingAddress) {
res.status(200);
res.json({
address: shippingAddress.address,
city: shippingAddress.city,
postalCode: shippingAddress.postalCode,
county: shippingAddress.country,
email: shippingAddress.userEmail,
});
} else {
res.status(404);
throw new Error("Address not found");
}
} else {
res.status(404);
throw new Error("User not found");
}
});
// #desc save address
// #route POST /api/shippingaddress
// #access Private
const saveAddress = asyncHandler(async (req, res) => {
const user = User.findById(req.user._id);
if (user) {
const { address, city, postalCode, country, email } = req.body;
const existAddress = await ShippingAddress.findOne({ userEmail: email });
if (existAddress) {
res.status(400);
throw new Error(
"User already has an address. If you want to change address, try CHANGE ADDRESS."
);
} else {
const createdAddress = await ShippingAddress.create({
user: req.user._id,
address,
city,
postalCode,
country,
userEmail: email,
});
if (createdAddress) {
res.status(201);
res.json({
address: createdAddress.address,
city: createdAddress.city,
postalCode: createdAddress.postalCode,
county: createdAddress.country,
email: createdAddress.userEmail,
});
} else {
res.status(400);
throw new Error("Address did not save");
}
}
} else {
res.status(404);
throw new Error("User not found");
}
});
// #desc change address
// #route PUT /api/shippingaddress
// #access Private
const changeAddress = asyncHandler(async (req, res) => {
const user = await User.findById(req.user._id);
if (user) {
const { email } = req.body;
const shippingAddress = await ShippingAddress.findOne({
userEmail: email,
});
if (shippingAddress) {
shippingAddress.address = req.body.address || shippingAddress.address;
shippingAddress.city = req.body.city || shippingAddress.city;
shippingAddress.postalCode =
req.body.postalCode || shippingAddress.postalCode;
shippingAddress.country = req.body.country || shippingAddress.country;
const updatedShippingAddress = await shippingAddress.save();
res.status(200);
res.json({
address: updatedShippingAddress.address,
city: updatedShippingAddress.city,
postalCode: updatedShippingAddress.postalCode,
county: updatedShippingAddress.country,
email: updatedShippingAddress.userEmail,
});
} else {
res.status(404);
throw new Error("Address not found");
}
} else {
res.status(404);
throw new Error("User not found");
}
});
export { getAddress, saveAddress, changeAddress };
authMiddleware file;
import jwt from "jsonwebtoken";
import User from "../models/userModel.js";
import asyncHandler from "express-async-handler";
const protect = asyncHandler(async (req, res, next) => {
let token = req.headers.token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
try {
// get token from req
token = req.headers.authorization.split(" ")[1];
// verify token
const decode = jwt.verify(token, process.env.JWT_SECRET);
// get user from token
req.user = await User.findById(decode.id).select("-password");
next();
} catch (error) {
res.status(401);
throw new Error("Not1 Authorized");
}
}
if (!token) {
res.status(401);
throw new Error("Not2 Authorized");
}
});
export default protect;
FOR FRONT-END;
shippingAction file;
import { createAsyncThunk } from "#reduxjs/toolkit";
import shippingServices from "./shippingServices";
// get address
export const getAddress = createAsyncThunk(
"shipping/get",
async (userInfo, thunkAPI) => {
try {
return await shippingServices.get(userInfo);
} catch (error) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
return thunkAPI.rejectWithValue(message);
}
}
);
// save address
export const saveAddress = createAsyncThunk(
"shipping/save",
async (addressInfo, thunkAPI) => {
try {
return await shippingServices.save(addressInfo);
} catch (error) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
return thunkAPI.rejectWithValue(message);
}
}
);
// update address
export const updateAddress = createAsyncThunk(
"shipping/update",
async (addressInfo, thunkAPI) => {
try {
return await shippingServices.update(addressInfo);
} catch (error) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
return thunkAPI.rejectWithValue(message);
}
}
);
shippingServices file;
import axios from "axios";
const SHIPPING_ADDRESS_URL = "/api/shippingaddress";
// save address
const save = async (addressInfo) => {
const config = {
headers: {
Authorization: `Bearer ${addressInfo.token}`,
},
};
const { data } = await axios.post(SHIPPING_ADDRESS_URL, addressInfo, config);
return data;
};
// get address
const get = async (userInfo) => {
const config = {
headers: {
Authorization: `Bearer ${userInfo.token}`,
},
};
const { data } = await axios.get(SHIPPING_ADDRESS_URL, userInfo, config);
return data;
};
// update address
const update = async (addressInfo) => {
const config = {
headers: {
Authorization: `Bearer ${addressInfo.token}`,
},
};
const { data } = await axios.put(SHIPPING_ADDRESS_URL, addressInfo, config);
return data;
};
const shippingServices = {
save,
get,
update,
};
export default shippingServices;
shippigPage file;
import React, { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import { Form, Button } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import FormContainer from "../components/FormContainer";
import Message from "../components/Message";
import Loader from "../components/Loader";
import { shippingSliceAction } from "../features/shipping/shippingSlice";
import { saveAddress, getAddress } from "../features/shipping/shippingAction";
function ShippingPage() {
const { user } = useSelector((state) => state.auth);
const { shippingAddress, isLoading, isSuccess, isError, message } =
useSelector((state) => state.shipping);
const [address, setAddress] = useState("");
const [city, setCity] = useState("");
const [postalCode, setPostalCode] = useState("");
const [country, setCountry] = useState("");
const [comMessage, setComMessage] = useState(null);
const dispatch = useDispatch();
const navigate = useNavigate();
useEffect(() => {
if (shippingAddress) {
setAddress(shippingAddress.address);
setCity(shippingAddress.city);
setPostalCode(shippingAddress.postalCode);
setCountry(shippingAddress.country);
} else {
const userInfo = {
token: user.token,
email: user.email,
};
dispatch(getAddress(userInfo));
}
}, []);
const submitHandler = (e) => {
e.preventDefault();
if (!user) {
navigate("/login");
} else {
if (!address || !city || !postalCode || !country) {
setComMessage("Please fill all fields");
setTimeout(() => setComMessage(null), 3000);
} else {
dispatch(
shippingSliceAction.takeAddress({
email: user.email,
address,
city,
postalCode,
country,
})
);
localStorage.setItem(
"userAddress",
JSON.stringify({
email: user.email,
address,
city,
postalCode,
country,
})
);
}
}
};
const saveContinue = () => {
if (!user) {
navigate("/login");
} else {
dispatch(
saveAddress({
email: user.email,
address,
city,
postalCode,
country,
token: user.token,
})
);
if (isSuccess) {
setComMessage("Your Address Saved");
setTimeout(() => dispatch(shippingSliceAction.reset()), 3000);
setTimeout(() => setComMessage(null), 3000);
setTimeout(() => navigate("/payment"), 4000);
}
}
};
return (
<FormContainer>
<h1>Shipping</h1>
{comMessage && <Message variant="danger">{comMessage}</Message>}
<Form onSubmit={submitHandler}>
<Form.Group controlId="address">
<Form.Label>Address</Form.Label>
<Form.Control
type="text"
placeholder="Enter Address"
value={address}
onChange={(e) => setAddress(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId="city">
<Form.Label>City</Form.Label>
<Form.Control
type="text"
placeholder="Enter City"
value={city}
onChange={(e) => setCity(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId="postalCode">
<Form.Label>Postal Code</Form.Label>
<Form.Control
type="number"
placeholder="Enter Postal Code"
value={postalCode}
onChange={(e) => setPostalCode(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId="country">
<Form.Label>Country</Form.Label>
<Form.Control
type="text"
placeholder="Enter Country"
value={country}
onChange={(e) => setCountry(e.target.value)}
></Form.Control>
</Form.Group>
<Button className="shippingButton" type="submit" variant="primary">
Continue without saving
</Button>
{isLoading && <Loader />}
{isSuccess && <Message variant="success"></Message>}
{isError && <Message variant="danger">{message}</Message>}
<Button
className="shippingButton save"
type="button"
variant="secondary"
onClick={saveContinue}
>
Save my address and continue
</Button>
</Form>
</FormContainer>
);
}
export default ShippingPage;
// shippingServices.js
const { data } = await axios.get(SHIPPING_ADDRESS_URL, userInfo, config);
this should be
const { data } = await axios.get(SHIPPING_ADDRESS_URL, config);
Also stop using unnecessary packages like express-async-handler,
just cover entire middle-ware function body with try/catch block, call next(error) in catch block & it will work just fine.
I was struggling for several months to implement Cloudinary into a MERN web app, so I am running out of options to find the answer.
Basically, the problem here is that I don't have the knowledge to write successfully the necessary code to make it work.
Here is some insight:
I need to upload photos to Cloudinary for a Blog web page, (the problem is in the first two code files)
I was able to make it work for user's profilePics in the last two code files ( Settings.jsx & Settings.js ).. now I had to do almost the same,but that works for images in posts (Write.jsx & Posts.js ).
Feel free to ask for more info about
Front-End Write.jsx
import { useContext, useState } from "react";
import "./write.css";
import { Context } from "../../context/Context";
import { axiosInstance } from "../../config";
import { FcAddImage } from "react-icons/fc";
export default function Write() {
const [title, setTitle] = useState("");
const [desc, setDesc] = useState("");
const [file, setFile] = useState(null);
const [success, setSuccess] = useState(false);
const { user, dispatch } = useContext(Context);
const photo = user.photo;
console.log("post info", title, desc, file, user);
const handleSubmit = async (e) => {
e.preventDefault();
if (file) {
const data = new FormData();
data.append("id", user._id);
data.append("type", "file");
data.append("avatar", file);
try {
const res = await axiosInstance.post("/upload", "/posts", data);
setSuccess(true);
dispatch({ type: "UPDATE_SUCCESS", payload: res.data });
} catch (err) {
console.log(err);
dispatch({ type: "UPDATE_FAILURE" });
}
}
};
/*try {
await axiosInstance.post("/upload", data);
} catch (err) {}
}
try {
const res = await axiosInstance.post("/posts", newPost);
window.location.replace("/post/" + res.data._id);
} catch (err) {}*/
return (
<div className="write">
{file && (
<img
className="writeImg"
src={file ? URL.createObjectURL(file) : photo}
alt=""
/>
)}
<form className="writeForm" onSubmit={handleSubmit}>
<div className="writeFormGroup">
<label htmlFor="fileInput">
Image
<FcAddImage className="icon" />
</label>
<input
action="/:id"
method="POST"
type="file"
id="fileInput"
style={{ display: "none" }}
onChange={(e) => setFile(e.target.files[0])}
/>
<input
type="text"
placeholder="Title"
className="writeInput"
autoFocus={true}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
<div className="writeFormGroup">
<textarea
placeholder="Tell your story..."
type="text"
className="writeInput writeText"
onChange={(e) => setDesc(e.target.value)}
></textarea>
</div>
<button className="writeSubmit" type="submit">
Publish
</button>
{success && (
<span
style={{ color: "green", textAlign: "center", marginTop: "20px" }}
>
Post has been uploaded...
</span>
)}
</form>
</div>
);
}
Server-side Post.js
const User = require("../models/User");
const Post = require("../models/Post");
const cloudinary = require("../utils/cloudinary");
const upload = require("../utils/multer");
//UPLOAD FILE
router.post("/upload", upload.single("avatar"), async (req, res) => {
try {
// Upload image to cloudinary
const result = await cloudinary.uploader.upload(req.file.path);
//save changes
post.photo = result.secure_url;
res.status(200).json(savedPost);
} catch (err) {
res.status(500).json(err);
}
});
//CREATE POST
router.post("/", async (req, res) => {
const newPost = new Post(req.body);
try {
const savedPost = await newPost.save();
res.status(200).json(savedPost);
} catch (err) {
res.status(500).json(err);
}
});
//UPDATE POST
router.put("/:id", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (post.username === req.body.username) {
try {
const updatedPost = await Post.findByIdAndUpdate(
req.params.id,
{
$set: req.body,
},
{ new: true }
);
res.status(200).json(updatedPost);
} catch (err) {
res.status(500).json(err);
}
} else {
res.status(401).json("You can update only your post!");
}
} catch (err) {
res.status(500).json(err);
}
});
//DELETE POST
router.delete("/:id", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (post.username === req.body.username) {
try {
await post.delete();
res.status(200).json("Post has been deleted...");
} catch (err) {
res.status(500).json(err);
}
} else {
res.status(401).json("You can delete only your post!");
}
} catch (err) {
res.status(500).json(err);
}
});
//GET POST
router.get("/:id", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
res.status(200).json(post);
} catch (err) {
res.status(500).json(err);
}
});
//GET ALL POSTS
router.get("/", async (req, res) => {
const username = req.query.user;
const catName = req.query.cat;
try {
let posts;
if (username) {
posts = await Post.find({ username });
} else if (catName) {
posts = await Post.find({
categories: {
$in: [catName],
},
});
} else {
posts = await Post.find();
}
res.status(200).json(posts);
} catch (err) {
res.status(500).json(err);
}
});
module.exports = router;
Server-side Settings.js
//POST IMAGES
router.post("/upload", upload.single("avatar"), async (req, res) => {
console.log('/users/upload triggered')
try {
// Upload image to cloudinary
const result = await cloudinary.uploader.upload(req.file.path);
// Save user
User.findById(req.body.id, (err, user) => {
if (err) console.log(err)
user.profilePic = result.secure_url
user.save((err) => {
if (err) console.log(err)
res.json(user);
console.log('user saved')
})
});
} catch (err) {
console.log(err);
res.status(500).json(err);
}
});
I made conection to cloudinary changing the line
const res = await axiosInstance.post("/posts/upload", data);
but now, I can't post the 'posts', but is a step in the right direction
const handleSubmit = async (e) => {
e.preventDefault();
if (file) {
const data = new FormData();
data.append("id", user._id);
data.append("type", "file");
data.append("avatar", file);
try {
const res = await axiosInstance.post("/posts/upload", data);
setSuccess(true);
dispatch({ type: "UPDATE_SUCCESS", payload: res.data });
} catch (err) {
console.log(err);
dispatch({ type: "UPDATE_FAILURE" });
}
}
};
I'm trying to create login form with react and mongoDB
here is my controller:
authenticate: function (req, res, next) {
Admin.findOne({
username: req.body.username
}, function (err, adminInfo) {
if (err) {
next(err);
} else {
if (bcrypt.compareSync(req.body.password, adminInfo.password)) {
const token = jwt.sign({
id: adminInfo._id
},
req.app.get("secretKey"), {
expiresIn: "1h"
}
);
res.json({
status: "success",
message: "admin found!!!",
data: {
user: adminInfo,
token: token
},
});
} else {
res.json({
status: "error",
message: "Invalid email/password!!!",
data: null,
});
}
}
});
}
and here is my LoginForm.jsx:
const LoginForm = (props) => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [routeRedirect, setRouteRedirect] = useState(false);
const [error, setError] = useState(false);
const login = (e) => {
e.preventDefault();
const admin = {
username,
password,
};
axios
.post("/login/authenticate", admin)
.then((res) => {
if (res.data.errors) {
setError(true);
} else {
return null;
}
})
.catch((err) => console.log(err));
setRouteRedirect(true);
};
return (
<ContactWrapper>
<ContactContainer>
{routeRedirect ? (
<Fragment>Hello</Fragment>
) : (
<Fragment>
<Title>LOGIN</Title>
<LoginForm onSubmit={login}>
<FormLabel>Username:</FormLabel>
<FormInput
type="text"
name="username"
onChange={(e) => setUsername(e.target.value)}
/>
<FormLabel>Password:</FormLabel>
<FormInput
type="password"
name="password"
onChange={(e) => setPassword(e.target.value)}
/>
<LoginButton type="submit">Login</LoginButton>
</LoginForm>
</Fragment>
)}
</ContactContainer>
</ContactWrapper>
);
};
export default LoginForm;
How can I authenticate username and password when click on button?
I tried to put in wrong password and wrong username and it still give me the "Hello"
How can I fix this?
Thank you
Here is my github project if you want to look over my code:
https://github.com/nathannewyen/the-beuter
It seems like you call "setRouteRedirect(true)" no matter the result of the api call.
You should probably setRouteRedirect in the then function of your post if the result satisfies you.
This call
axios
.post("/login/authenticate", admin)
.then((res) => {
if (res.data.errors) {
setError(true);
} else {
return null;
}
})
.catch((err) => console.log(err));
Does not block the code, so after sending the request, setRouteRedirect will be called.
I set up a proxy to bypass CORS for the intended api in this react application. I'm having trouble to pass data from react component to proxy(nodeJS server). I've read a few links such as here and here but still have no clues.
/*React component*/
import React, { useState } from "react";
import axios from "axios";
export default function Mail() {
const [emailInput, setEmailInput] = useState('')
const getMail = () => {
axios.get("/list/members").then(json => {
console.log(json.data);
});
};
const subscribe = (email) => {
console.log('inside subscribe')
axios.post("/member", email)
.then(data => console.log('post succeeds'))
.catch(err => console.log(err))
}
const handleSubmit = e => {
e.preventDefault();
const email = {
email_address: `${emailInput}`,
status: "subscribed"
};
subscribe(email)
};
const handleChange = (e) => {
setEmailInput(e.target.value)
}
return (
<form onSubmit={handleSubmit}>
<input type="text" name="email" placeholder="enter your email" value={emailInput} onChange={handleChange}/>
<input type="submit" value="subscribe" />{" "}
</form>
);
}
In node server, I have
app.post("/member", (req, res) => {
const email = {
email_address: "axios1234#gmail.com",
status: "subscribed"
};
axios.post(
"https://<apilink>",
email,
{
withCredentials: true,
auth: {
username: "anystring",
password: "<apikey>"
}
}
).then(json => {
res.send(json.data)
}).catch(err => {
console.log(err);
})
});
I've checked that my conduit between react front end app and proxy server is working. I also examined both req and res in app.post("/member", (req, res) but found thatreq.body is undefined and couldn't find the email object that was passed in from react function component. Did I miss anything here?
Are you using a body-parser? If not, install body-parser and then change your code to this:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post("/member", (req, res) => {
const email = req.body.email_address;
axios.post(
"https://<apilink>",
email,
{
withCredentials: true,
auth: {
username: "anystring",
password: "<apikey>"
}
}
).then(json => {
res.send(json.data)
}).catch(err => {
console.log(err);
})
});