My code is not working, i am using node and React, the axios is trying to connect with the backend, but it fail.
When i try the connect in console:
image of firefox console
my code is: frontend/pages/login/index.js
import { FiLogIn } from 'react-icons/fi'
import {Link } from 'react-router-dom'
import api from '../../services/api'
import './styles.css'
export default function Login() {
const [name, setName] = useState('')
const [password, setPassword] = useState('')
async function handleLogin(e) {
e.preventDefault()
let data = ({
name,
password}
)
try {
let response = await api.post('session', data)
} catch(err){
console.log(err)
}
}
return (
<div className="login-conteiner">
<header>
<nav>
<div className="navlinks">
<Link to="/"><div className="li">Vega</div></Link>
<Link to="about.html"><div className="li">Sobre</div></Link>
</div>
</nav>
</header>
<main className="login">
<div className="heading">
<span className="blackblock"><h1>Vega Leads</h1></span>
<h2>Visualize todos os Leads <br /> da sua Instiuição <br /> e torne em alunos.</h2><br />
</div>
<div>
<form className="loginForm" id="form" onSubmit={handleLogin}>
<div className="loginItem"><label htmlFor="login">Login </label><input className="formInput" type="text" name="login" id="login"
value={name}
onChange={e => setName(e.target.value)} /></div><br />
<div className="loginItem"><label htmlFor="senha">Senha </label><input className="formInput" type="password" name="password" id="password"
value={password}
onChange={ e => setPassword(e.target.value) } /></div><br />
<button type="submit" className="startButton" id="postForm">Enviar <FiLogIn size={25} color="#11548f" /></button>
</form>
</div>
</main>
</div>
)}
Axios api: frontend/services/api.js
const api = axios.create({
baseURL: 'http://localhost:3333',
})
export default api
If you need more files to resolve my problem, ask me.
Thanks
i resolved the problem.
the problem is in the index of my backend (backend/src/index.js)
i forget the CORS module.
it is my code:
const routes = require('./routes')
const cors = require('cors')
const app = express()
app.use(cors())
app.use(express.json())
app.use(routes)
app.listen(3333)
Related
When I use the postman backend it works fine. But when using React and trying to add data to the database gives a 400 error.
When I use the console.log(newpost) it gives a new post object on the console. But I can't send the data to the database. How to fix this?
postman image
My React Code:
import React, {useState} from "react";
import axios from "axios";
export default function AddPost(){
const [topic,setTopic] = useState("")
const [dec,setDec] = useState("")
const [cate,setCate] = useState("")
function sendData(e){
e.preventDefault();
const newpost = {
topic,
dec,
cate
}
axios.post("http://localhost:8000/post/save",newpost)
.then(()=>{
alert("post added")
setTopic ("")
setDec ("")
setCate("")
}).catch((err)=>{
alert(`Not inserted ${err}`)
})
}
return(
<div className="container">
<form onSubmit={sendData} >
<div className="mb-3">
<label htmlFor="name" className="form-label">topic</label>
<input type="test" className="form-control" id="name" aria-describedby="emailHelp" onChange={(e)=>{
setTopic(e.target.value)
}} />
</div>
<div className="mb-3">
<label htmlFor="Age" className="form-label">description</label>
<input type="test" className="form-control" id="Age" onChange={(e)=>{
setDec(e.target.value)
}}/>
</div>
<div className="mb-3">
<label htmlFor="Gender" className="form-label">postCategory</label>
<input type="test" className="form-control" id="Gender" onChange={(e)=>{
setCate(e.target.value)
}}/>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
<div/>
</div>
)
}
As per your postman's request, the request body is not correctly being passed from react code.The expected key name doesn't match. You need to change newpost variable as follows:
const newpost = {
topic,
description: dec,
postCategory: cate
}
Try adding named keys.
For example:
const newpost = {
topic: 'test',
dec: 'test',
cate: 'test'
}
So ive got this error, im guessing its something with my use navigate, but im not shure.
Ive have read alot and searched for the solution but i cant find any way to solve the issue.
The issue only comes after ive have logged in. At the moment i dont have any access token on the backend.
react_devtools_backend.js:4026 Warning: Cannot update a component (BrowserRouter) while rendering a different component (Login). To locate the bad setState() call inside Login, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
at Login (http://localhost:3000/static/js/bundle.js:3571:82)
at div
at LoginPage
at Routes (http://localhost:3000/static/js/bundle.js:129199:5)
at Router (http://localhost:3000/static/js/bundle.js:129132:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:127941:5)
import React from 'react';
import { useRef, useState, useEffect } from 'react'
// import { useContext } from 'react'
//import AuthContext from './context/AuthProvider';
import axios from './api/axios';
const LOGIN_URL = '/login';
const REG_URL = '/newUser'
export default function Login() {
const [authMode, setAuthMode] = useState("signin");
const changeAuthMode = () => {
setAuthMode(authMode === "signin" ? "signup" : "signin");
}
//const { setAuth } = useContext(AuthContext);
const userRef = useRef();
const errRef = useRef();
const [userName, setUserName] = useState("");
const [password, setPassword] = useState("");
const [errMsg, setErrMsg] = useState('');
const [success, setSuccess] = useState(false);
const [register, setRegister] = useState(false);
useEffect(() => {
userRef.current.focus();
}, [])
useEffect(() => {
setErrMsg('');
}, [userName, password])
const handleRegister = (e) => {
// prevent the form from refreshing the whole page
e.preventDefault();
// set configurations
const RegConfiguration = {
method: "post",
url: REG_URL,
data: {
userName,
password,
},
};
// make the API call
axios(RegConfiguration)
.then((result) => {
setRegister(true);
})
.catch((error) => {
error = new Error();
});
};
///HANDLE Login part.
const handleLogin = async (e) => {
e.preventDefault();
try {
await axios.post(LOGIN_URL,
JSON.stringify({ userName, password }),
{
headers: { 'Content-type': 'application/json' },
withCredentials: false,
}
);
//const token = response?.data?.token;
//setAuth({ userName, password, token })
//console.log(JSON.stringify(respone));
setUserName('');
setPassword('');
setSuccess(true);
} catch (err) {
if (!err?.response) {
setErrMsg('No Server Response');
} else if (err.response?.status === 400) {
setErrMsg('Missing Username or Password');
} else if (err.response?.status === 401) {
setErrMsg('Unauthorized');
}
else {
setErrMsg('Login Failed');
}
errRef.current.focus();
}
}
const Navigate = useNavigate();
if (authMode === "signin") {
return (
<> {success ? (
Navigate('/authlog')
) : (
<div className="Auth-form-container">
<form className="Auth-form" >
<div className="Auth-form-content">
<h3 className="Auth-form-title">Sign In</h3>
<div className="text-center">
Not registered yet?{" "}
<span className="link-primary" onClick={changeAuthMode} >
Sign Up
</span>
</div>
<div className="form-group mt-3">
<label>Username </label>
<input
className="form-control mt-1"
id='userName'
ref={userRef}
name="userName"
value={userName}
placeholder="username"
onChange={(e) => setUserName(e.target.value)}
/>
</div>
<div className="form-group mt-3">
<label>Password</label>
<input
className="form-control mt-1"
name="password"
type="password"
id='password'
value={password}
placeholder="password"
required
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="d-grid gap-2 mt-3">
<button
type="submit"
className="btn btn-primary"
onClick={(e) => handleLogin(e)}
>
Logga in
</button>
<p ref={errRef} className={errMsg ? "errmsg" : "offscreen"} aria-live="assertive">{errMsg}</p>
</div>
</div>
</form>
</div>
)}</>
)
}
// "Register page"
return (
<div className="Auth-form-container">
<form className="Auth-form" onSubmit={(e) => handleRegister(e)}>
<div className="Auth-form-content">
<h3 className="Auth-form-title">Sign In</h3>
<div className="text-center">
Already registered?{" "}
<span className="link-primary" onClick={changeAuthMode}>
Go to Sign In
</span>
</div>
<div className="form-group mt-3">
<label>Register Your Username here</label>
<input
className="form-control mt-1"
name="userName"
value={userName}
placeholder="ure username here:"
onChange={(event) => setUserName(event.target.value)}
/>
</div>
<div className="form-group mt-3">
<label>Register Youre password</label>
<input
className="form-control mt-1"
type="password"
name="password"
value={password}
placeholder="ure password here"
onChange={(event) => setPassword(event.target.value)}
/>
</div>
<div className="d-grid gap-2 mt-3">
<button type="submit" className="btn btn-primary" onClick={handleRegister}>
Registera
</button>
{/* display success message */}
{register ? (
<p className="text-success">You Are Now Registered Successfully</p>
) : (
<p className="text-danger">Please register your account here</p>
)}
</div>
</div>
</form>
</div>
);
}
Hello guys so i tried to make global state so the other page can use the state. The problem is i got an error that says:
Login.js:18 Uncaught TypeError: Cannot destructure property 'emailLog' of '(0 , react__WEBPACK_IMPORTED_MODULE_0__.useContext)(...)' as it is undefined.
Im doing this because i want the email from user after logged in and pass them to another page so that i can display the logged in user.
App.js:
export const EmailUser = React.createContext();
function App() {
Axios.defaults.withCredentials = true;
const [invoice, setInvoice] = useState("");
const [currency, setCurrency] = useState("IDR");
const [myFile, setMyFile] = useState("");
const [emailLog, setEmailLog] = useState("");
return (
<EmailUser.Provider value={{ emailLog, setEmailLog }}>
<div className="App">
<BasicExample />
<div className="formInput">
<form method="POST" encType="multipart/form-data" action="http://localhost:3001/upload">
<div className="textUser"></div>
<input
className="inputForm"
defaultValue={emailLog}
type="email"
disabled
name="email"
/>
<input className="inputForm" type="number" placeholder="Invoice No" name="InvoiceNo" />
<input className="inputForm" type="date" name="Invoice_Date" />
<input className="inputForm" type="text" placeholder="Description" name="Description" />
<select
className="selectBox"
name="Currency"
onChange={(e) => {
setCurrency(e.target.value);
}}
>
<option value="IDR">IDR</option>
<option value="USD">USD</option>
<option value="YEN">YEN</option>
</select>
<input className="inputForm" type="number" placeholder="Amount" name="Amount" />
<input
className="custom-file-upload"
multiple
type="file"
name="DocumentFile"
onChange={(e) => {
setMyFile(e.target.value);
}}
/>
<button className="btnSubmit">Submit</button>
</form>
</div>
</div>
</EmailUser.Provider>
);
}
export default App;
Login.js
const Login = () => {
let navigate = useNavigate();
const { emailLog, setEmailLog } = useContext(EmailUser);
const [passwordLog, setPasswordLog] = useState("");
const [loginStatus, setLoginStatus] = useState("");
Axios.defaults.withCredentials = true;
const login = (e) => {
e.preventDefault();
Axios.post("http://localhost:3001/login", {
email: emailLog,
password: passwordLog,
}).then((response) => {
console.log(response);
if (response.data.message) {
alert(response.data.message);
} else {
setLoginStatus(response.data[0].email);
alert("Redirecting");
navigate("/home");
}
});
};
console.log(emailLog);
useEffect(() => {
Axios.get("http://localhost:3001/login").then((response) => {
if (response.data.loggedIn == true) {
setLoginStatus(response.data.email[0].email);
}
});
});
return (
<div>
<img className="wave" src={Wave} />
<img className="wave2" src={WaveV2} />
<div className="wrapper">
<div className="img">{/* <img src={Background}/> */}</div>
<div className="register-content">
<div className="registerForm">
<img src={Avatar} />
<h2 className="title">Welcome</h2>
<div className="input-div one">
<div className="i">
<i className="fas fa-user">
<GrMail />
</i>
</div>
<div className="div">
<input
type="email"
className="input"
placeholder="Email"
required
onChange={(e) => {
setEmailLog(e.target.value);
}}
/>
</div>
</div>
<div className="input-div pass">
<div className="i">
<i className="fas fa-lock">
<AiFillLock />
</i>
</div>
<div className="div">
<input
type="password"
className="input"
placeholder="Password"
required
onChange={(e) => {
setPasswordLog(e.target.value);
}}
/>
</div>
</div>
Don't have an account ?
<button type="submit" className="btn" onClick={login}>
Login
</button>
</div>
</div>
</div>
</div>
);
};
export default Login;
EmailUser context works only with the components that are children of EmailUser.Provider, and it doesn't seem to be the case for Login component. An easy way is to create a separate component, in some EmailUserProvider.js, like so:
import {createContext, useState} from "react"
export const EmailUser = createContext();
export default function EmailUserProvider({children}) {
const [emailLog, setEmailLog] = useState("");
return (
<EmailUser.Provider value={{ emailLog, setEmailLog }}>
{children}
</EmailUser.Provider>
);
}
And make it wrap all the components that would consume it. If I assume all my components and routes are rendered in App and want the context to be global, I would do so:
<EmailUserProvider>
<App/>
</EmailUserProvider>
I am trying to create a register and login page where the registered user's details are setn to the database and then from there they are used to verify login.
The sign up button is supposed to send data to the database, hence registering a user. After that, in the login form the data os authenticated and the user logs in.
I haven't gotten to the login part, still stuck on the sign up part.
I don't get any errors displayed, it is just that my data is not being fed to the database.
index.js for nodejs:
//var { app } = require("cli");
const express = require("express");
const mysql = require("mysql");
const cors = require("cors");
app = express();
app.use(express.json());
app.use(cors());
const db = mysql.createConnection({
user: "root",
host: "localhost",
password: "",
database: "crm database",
});
app.post("/register", (req, res) => {
const CompanyCode = req.body.CompanyCode;
const UserID = req.body.UserID;
const UserFullName = req.body.UserFullName;
const UserDetail = req.body.UserDetail;
const LoginID = req.body.LoginID;
const Password = req.body.Password;
const ConfirmPassword = req.body.ConfirmPassword;
const UserPin = req.body.UserPin;
const UserEmailID = req.body.UserEmailID;
db.query(
"INSERT INTO usermst (CmpnyCode,UserID,UserFullName,UserDetail,LoginID,Password,UserPin,UserEmailID) VALUES (?,?,?,?,?,?,?,?)",
[
CompanyCode,
UserID,
UserFullName,
UserDetail,
LoginID,
Password,
UserPin,
UserEmailID,
],
(err, result) => {
console.log(err);
}
);
});
app.listen(8000, () => {
console.log("Server running on port 8000");
});
app.js for react js:
import "bootstrap/dist/css/bootstrap.min.css";
import React, { useState } from "react";
//import { BrowserRouter, Switch, Route } from "react-router-dom";
import "./App.css";
import axios from "axios";
function App() {
const [CompanyCodeReg, setCompanyCodeReg] = useState("");
const [UserIDReg, setUserIDReg] = useState("");
const [UserFullNameReg, setUserFullNameReg] = useState("");
const [UserDetailReg, setUserDetailReg] = useState("");
const [LoginIDReg, setLoginIDReg] = useState("");
const [PasswordReg, setPasswordReg] = useState("");
const [ConfirmPasswordReg, setConfirmPasswordReg] = useState("");
const [UserPinReg, setUserPinReg] = useState("");
const [UserEmailIDReg, setUserEmailIDReg] = useState("");
const register = () => {
axios
.post("http://localhost8000/register", {
CompanyCode: CompanyCodeReg,
UserID: UserIDReg,
UserFullName: UserFullNameReg,
UserDetail: UserDetailReg,
LoginID: LoginIDReg,
Password: PasswordReg,
ConfirmPassword: ConfirmPasswordReg,
UserPin: UserPinReg,
UserEmailID: UserEmailIDReg,
})
.then((response) => {
console.log(response);
});
};
return (
<div className="App">
<nav className="navbar navbar-expand navbar-light fixed-top">
<div className="container">Home</div>
</nav>
<div className="auth-wrapper">
<div className="auth-inner">
<form>
<h3>Sign Up</h3>
<div className="form-group">
<label>Company Code</label>
<input
type="text"
className="form-control"
placeholder="CompanyCode"
onChange={(e) => {
setCompanyCodeReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>User ID</label>
<input
type="text"
className="form-control"
placeholder="UserID"
onChange={(e) => {
setUserIDReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>User Full Name</label>
<input
type="text"
className="form-control"
placeholder="UserFullName"
onChange={(e) => {
setUserFullNameReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>User Detail</label>
<input
type="text"
className="form-control"
placeholder="UserDetail"
onChange={(e) => {
setUserDetailReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>Login ID</label>
<input
type="text"
className="form-control"
placeholder="LoginID"
onChange={(e) => {
setLoginIDReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>Password</label>
<input
type="password"
className="form-control"
placeholder="Password"
onChange={(e) => {
setPasswordReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>Confirm Password</label>
<input
type="password"
className="form-control"
placeholder=" ConfirmPassword"
onChange={(e) => {
setConfirmPasswordReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>User Pin</label>
<input
type="Text"
className="form-control"
placeholder="UserPin"
onChange={(e) => {
setUserPinReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>UserEmailID</label>
<input
type="email"
className="form-control"
placeholder="UserEmailID"
onChange={(e) => {
setUserEmailIDReg(e.target.value);
}}
/>
</div>
<button className="btn btn-primary btn-block" onClick={register}>
Sign Up
</button>
</form>
</div>
<div className="auth-inner">
<form>
<h3>Log In</h3>
<div className="form-group">
<label>Login ID</label>
<input
type="text"
className="form-control"
placeholder="First Name"
/>
</div>
<div className="form-group">
<label>Password</label>
<input
type="password"
className="form-control"
placeholder="Password"
/>
</div>
<button className="btn btn-primary btn-block">Login</button>
</form>
</div>
</div>
</div>
);
}
export default App;
You have to send the response back to the client, you can do so with the res object like
res.json({ result });
app.post("/register", (req, res) => {
const CompanyCode = req.body.CompanyCode;
const UserID = req.body.UserID;
const UserFullName = req.body.UserFullName;
const UserDetail = req.body.UserDetail;
const LoginID = req.body.LoginID;
const Password = req.body.Password;
const ConfirmPassword = req.body.ConfirmPassword;
const UserPin = req.body.UserPin;
const UserEmailID = req.body.UserEmailID;
db.query(
"INSERT INTO usermst (CmpnyCode,UserID,UserFullName,UserDetail,LoginID,Password,UserPin,UserEmailID) VALUES (?,?,?,?,?,?,?,?)",
[
CompanyCode,
UserID,
UserFullName,
UserDetail,
LoginID,
Password,
UserPin,
UserEmailID,
],
(err, result) => {
console.log(err);
// You have missed this line
res.json({ result });
}
);
});
I just realized that I was violating my own database foreign key constraints.
I added the following line:
db.connect((err) => {
if (err) {
console.log(err);
}
console.log("Connected to MySQL Server!");
});```
after creating the database connection and it displayed to me what was going wrong.
I am currently learning to build e-commerce webapp with react, the tutorial material I am using used stripe as payment gateway, but I want to use Paystack instead. but I don't know how to code my way through it, perhaps there's a universal method to integrate a payment gateway into react?
Install react-paystack library using NPM or YARN . And this is all you need for the popup setup for more on this in detail view the Paystack documentation from where this code was posted initially Paystack React.
At the moment I can only see a popup implementation for Paystack since Paystack.js is now deprecated.
import React, { useState } from "react"
import { PaystackButton } from "react-paystack"
import "./App.css"
const App = () => {
const publicKey = "pk_test_4fc00f3df93a5f8efeb57bdd70605937312a029e"
const amount = 1000000
const [email, setEmail] = useState("")
const [name, setName] = useState("")
const [phone, setPhone] = useState("")
const componentProps = {
email,
amount,
metadata: {
name,
phone,
},
publicKey,
text: "Buy Now",
onSuccess: () => {
setEmail("")
setName("")
setPhone("")
},
onClose: () => alert("Wait! You need this oil, don't go!!!!"),
}
return (
<div className="App">
<div className="container">
<div className="item">
<div className="overlay-effect"></div>
<img
className="item-image"
src="https://images.unsplash.com/photo-1526947425960-945c6e72858f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2850&q=80"
alt="product"
/>
<div className="item-details">
<p className="item-details__title">Coconut Oil</p>
<p className="item-details__amount">NGN {amount / 100}</p>
</div>
</div>
<div className="checkout">
<div className="checkout-form">
<div className="checkout-field">
<label>Name</label>
<input
type="text"
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="checkout-field">
<label>Email</label>
<input
type="text"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="checkout-field">
<label>Phone</label>
<input
type="text"
id="phone"
value={phone}
onChange={(e) => setPhone(e.target.value)}
/>
</div>
<PaystackButton className="paystack-button" {...componentProps} />
</div>
</div>
</div>
</div>
)
}
export default App