having issues running my react app locally - node.js

I have added my backend to heroku and my frontend to netlify, however when I'm trying to run my app whether it is locally or via netlify I'm getting the below error message when logging in or/and registering:
Uncaught Error: Element type is invalid: expected a string (for
built-in components) or a class/function (for composite components)
but got: object. You likely forgot to export your component from the
file it's defined in, or you might have mixed up default and named
imports.
what am I missing?
see below my app.js and signin.js for the frontend:
here is my APP.JS
import React, {Component} from 'react';
// import Clarifai from 'clarifai';
import Navigation from './components/Navigation/Navigation';
import Logo from './components/Logo/Logo';
import ImageLinkForm from './components/ImageLinkForm/ImageLinkForm';
import FaceRecognition from './components/FaceRecognition/FaceRecognition';
import Rank from './components/Rank/Rank';
import Signin from './components/Signin/Signin';
import Register from './components/Register/Register';
import './App.css';
const intialState = {
input: '',
imageUrl: '',
box: {},
route: 'signin',
isSignedIn: false,
user: {
id: '',
name: '',
email: '',
entries: 0,
joined: ''
}
}
class App extends Component {
constructor() {
super();
this.state = intialState
}
loadUser = (data) => {
this.setState({user: {
id: data.id,
name: data.name,
email: data.email,
entries: data.entries,
joined: data.joined
}})
}
calculateFaceLocation =(data) => {
const clarifaiFace = data.outputs[0].data.regions[0].region_info.bounding_box;
const image = document.getElementById('inputimage');
const width = Number(image.width);
const height = Number(image.height);
return {
leftCol: clarifaiFace.left_col * width,
topRow: clarifaiFace.top_row * height,
rightCol: width - clarifaiFace.right_col * width,
bottomRow: height - clarifaiFace.bottom_row * height,
};
}
displayFaceBox = (box) => {
console.log(box)
this.setState({box: box});
}
onInputChange = (event) => {
this.setState({input: event.target.value})
}
onButtonSubmit = () => {
this.setState({imageUrl: this.state.input})
fetch('https://ancient-sea-46547.herokuapp.com/imageurl', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
input: this.state.input
})
})
.then(response => response.json())
.then( response => {
if (response) {
fetch('https://ancient-sea-46547.herokuapp.com/image', {
method: 'put',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
id: this.state.user.id
})
})
.then(response => response.json())
.then(count => {
this.setState(Object.assign(this.state.user, { entries: count}))
})
.catch(console.log)
}
this.displayFaceBox(this.calculateFaceLocation(response))
})
.catch(err => console.log(err));
}
onRouteChange = (route) => {
if (route === 'signout') {
this.setState(intialState)
} else if (route === 'home') {
this.setState({isSignedIn: true})
}
this.setState({route:route});
}
render() {
return (
<div className="App">
<Navigation isSignedIn={this.state.isSignedIn} onRouteChange={this.onRouteChange} />
{ this.state.route === 'home'
? <div>
<Logo />
<Rank
name={this.state.user.name}
entries={this.state.user.entries}/>
<ImageLinkForm
onInputChange={this.onInputChange}
onButtonSubmit={this.onButtonSubmit} />
<FaceRecognition box={this.state.box} imageUrl={this.state.imageUrl}/>
</div>
:(
this.state.route === 'signin'
?<Signin loadUser={this.loadUser} onRouteChange={this.onRouteChange} />
:<Register loadUser={this.loadUser} onRouteChange={this.onRouteChange} />
)
}
</div>
);
}
}
export default App;
SIGNIN.JS
import React from 'react';
class Signin extends React.Component {
constructor(props) {
super(props);
this.state = {
signInEmail: '',
signInPassword: ''
}
}
onEmailChange = (event) => {
this.setState({signInEmail: event.target.value})
}
onPasswordChange = (event) => {
this.setState({signInPassword: event.target.value})
}
onSubmitSignIn = () => {
fetch('https://ancient-sea-46547.herokuapp.com/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword
})
})
.then(response => response.json())
.then(user => {
if (user.id) {
this.props.loadUser(user);
this.props.onRouteChange('home');
}
})
}
render() {
const { onRouteChange} = this.props;
return (
<article className="br3 ba b--black-10 mv4 w-100 w-50-m w-25-l mw6 shadow-5 center">
<main className="pa4 black-80">
<div className="measure">
<fieldset id="sign_up" className="ba b--transparent ph0 mh0">
<legend className="f1 fw6 ph0 mh0">Sign In</legend>
<div className="mt3">
<label className="db fw6 lh-copy f6" for="email-address">Email</label>
<input
className="pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100"
type="email"
name="email-address"
id="email-address"
onChange={this.onEmailChange}
/>
</div>
<div className="mv3">
<label className="db fw6 lh-copy f6" for="password">Password</label>
<input
className="b pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100"
type="password"
name="password"
id="password"
onChange={this.onPasswordChange}
/>
</div>
</fieldset>
<div className="">
<input
onClick={this.onSubmitSignIn}
className="b ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib"
type="submit"
value="Sign in" />
</div>
<div className="lh-copy mt3">
<p onClick={() => onRouteChange('register')} className="f6 link dim black db pointer">Register</p>
</div>
</div>
</main>
</article>
);
}
}
export default Signin;
here is my server.js
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');
const register = require('./controllers/register');
const signin = require('./controllers/signin');
const profile = require('./controllers/profile');
const image = require('./controllers/image');
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '1';
const db = knex({
client: 'pg',
connection: {
connectionString : process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
}
});
const app = express();
app.use(bodyParser.json())
app.use(cors())
app.get('/', (req, res) => {res.send('it is working') })
app.post('/signin', (req, res) => {signin.handleSignin(req, res, db, bcrypt)})
app.post('/register', (req, res) => {register.handleRegister(req, res, db, bcrypt)})
app.get('/profile/:id', (req, res) => {profile.handleProfile(req, res, db)})
app.put('/image', (req, res) => {image.handleImage(req, res, db)})
app.post('/imageurl', (req, res) => {image.handleApiCall(req, res)})
app.listen(process.env.PORT || 3001, () => {
console.log(`app is running on port ${process.env.PORT}`)
})
register.js
import React from 'react';
class Register extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
name: ''
}
}
onNameChange = (event) => {
this.setState({name: event.target.value})
}
onEmailChange = (event) => {
this.setState({email: event.target.value})
}
onPasswordChange = (event) => {
this.setState({password: event.target.value})
}
onSubmitSignIn = () => {
fetch('https://ancient-sea-46547.herokuapp.com/register', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.email,
password: this.state.password,
name: this.state.name
})
})
.then(response => response.json())
.then(user => {
if (user.id) {
this.props.loadUser(user)
this.props.onRouteChange('home');
}
})
}
render() {
return (
<article className="br3 ba b--black-10 mv4 w-100 w-50-m w-25-l mw6 shadow-5 center">
<main className="pa4 black-80">
<div className="measure">
<fieldset id="sign_up" className="ba b--transparent ph0 mh0">
<legend className="f1 fw6 ph0 mh0">Register</legend>
<div className="mt3">
<label className="db fw6 lh-copy f6" for="name">Name</label>
<input
className="pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100"
type="text"
name="name"
id="name"
onChange={this.onNameChange}
/>
</div>
<div className="mt3">
<label className="db fw6 lh-copy f6" for="email-address">Email</label>
<input
className="pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100"
type="email"
name="email-address"
id="email-address"
onChange={this.onEmailChange}
/>
</div>
<div className="mv3">
<label className="db fw6 lh-copy f6" for="password">Password</label>
<input
className="b pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100"
type="password"
name="password"
id="password"
onChange={this.onPasswordChange}
/>
</div>
</fieldset>
<div className="">
<input
onClick={this.onSubmitSignIn}
className="b ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib"
type="submit"
value="Register" />
</div>
<div className="lh-copy mt3">
</div>
</div>
</main>
</article>

Related

Checkbox doesn't change after clicking React

I need to update options so that later useCallback will process it, but when I click on the checkbox, nothing changes.
But if you comment out setOptions, then the checkbox changes
const [options, setOptions] = useState({
s22: {value: 'TRUE', s: 22},
s23: {value: 'TRUE', s: 23},
s24: {value: 'TRUE', s: 24}
})
const changeFilter = event => {
setOptions({ ...options, [event.target.name]: {
value: event.target.checked.toString().toUpperCase(),
s: event.target.value
}
})
}
<div id="filter">
<p>
<label>
<input name="s22" type="checkbox" value="22" onChange={changeFilter} />
<span>УК</span>
</label>
</p>
<p>
<label>
<input name="s23" type="checkbox" value="23" onChange={changeFilter} />
<span>ФК</span>
</label>
</p>
<p>
<label>
<input name="s24" type="checkbox" value="24" onChange={changeFilter} />
<span>ФТ</span>
</label>
</p>
</div>
Found similar questions but there was a problem with preventDefault
Full code
import React, {useCallback, useContext, useEffect, useState} from 'react'
import {useHttp} from '../hooks/http.hook'
import {AuthContext} from '../context/AuthContext'
import {Loader} from '../components/Loader'
export const TreePage = () => {
const [tree, setTree] = useState([])
const [options, setOptions] = useState({
s22: {value: 'TRUE', s: 22},
s23: {value: 'TRUE', s: 23},
s24: {value: 'TRUE', s: 24}
})
const {loading, request} = useHttp()
const {token} = useContext(AuthContext)
const fetchTree = useCallback(async () => {
try {
const fetched = await request('/api/tree', 'GET', options, {
Authorization: `Bearer ${token}`
})
setTree(fetched)
} catch (e) {}
}, [token, request, options])
useEffect(() => {
fetchTree()
}, [fetchTree])
useEffect(() => {
var zoom = 1;
var zoomStep = 0.1;
document.getElementById("zoomIn").addEventListener("click",function(){
zoom += zoomStep; document.getElementById("zoomtext").style.transform = "scale("+zoom+")";
});
document.getElementById("zoomOut").addEventListener("click",function(){
if(zoom > zoomStep){
zoom -= zoomStep;
document.getElementById("zoomtext").style.transform = "scale("+zoom+")";
}
});
})
const changeFilter = event => {
setOptions({ ...options, [event.target.name]: {
value: event.target.checked.toString().toUpperCase(),
s: event.target.value
}
})
}
if (loading) {
return <Loader/>
}
return (
<>
{!loading &&
<div className="row">
<div className="col s6 offset-s3">
<div id="filter">
<p>
<label>
<input name="s22" type="checkbox" value="22" onChange={changeFilter} />
<span>УК</span>
</label>
</p>
<p>
<label>
<input name="s23" type="checkbox" value="23" onChange={changeFilter} />
<span>ФК</span>
</label>
</p>
<p>
<label>
<input name="s24" type="checkbox" value="24" onChange={changeFilter} />
<span>ФТ</span>
</label>
</p>
</div>
<div dangerouslySetInnerHTML={{__html: tree}}></div>
</div>
</div>
}
</>
)
}

400 bad request while submitting form

i am getting an error like 400 bad request while submitting form don't know whats going on wrong please help to solve my error
This img will help you to catch error
https://ibb.co/X8NKGzd and https://ibb.co/Y8fXsBj
addMovie.js
This is my frontend addmovie logic
import React,{useState} from 'react';
import Navbar from '../pages/Navbar';
import Footer from '../pages/Footer';
import {Link} from 'react-router-dom';
import {isAuthenticated} from '../Auth/index';
import {addMovie} from '../Admin/adminapicall';
const AddMovie = () => {
const {user,token} = isAuthenticated();
const [values,setValues] = useState({
movie_name:'',
actor:'',
country_of_origin:'',
duration:'',
director:'',
photo:'',
loading:false,
error:'',
addedMovie:'',
getRedirect:false,
// formData:''
})
const {movie_name,actor,country_of_origin,duration,director,photo,loading,error,addedMovie,getRedirect} = values;
const handleChange = name => event => {
const value = name === "photo" ? event.target.files[0] : event.target.value
// formData.set(name,value);
setValues({...values,[name]:value})
};
const onSubmit = (e) => {
e.preventDefault();
setValues({...values,error:'',loading:true})
addMovie(user._id,token,JSON.stringify(values)).then(data =>{
if(data.error){
setValues({...values,error:data.error})
}else{
setValues({
...values,
movie_name:'',
actor:'',
country_of_origin:'',
duration:'',
director:'',
photo:'',
loading:false,
addedMovie: data.movie_name
})
}
})
}
const successMessage = () => (
<div className='alert alert-success mt-3'
style={{display : addedMovie ? '' : 'none'}}>
<h4>{addedMovie} added successfully</h4>
</div>
)
// const successMessage = () => {
// }
const addMovieForm = () => (
<form >
<span>Post photo</span>
<div className="form-group">
<label className="btn btn-block btn-success">
<input
onChange={handleChange("photo")}
type="file"
name="photo"
accept="image"
placeholder="choose a file"
/>
</label>
</div>
<div className="form-group">
<input
onChange={handleChange("movie_name")}
name="photo"
className="form-control"
placeholder="movie_name"
value={movie_name}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("actor")}
name="photo"
className="form-control"
placeholder="actor"
value={actor}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("duration")}
type="number"
className="form-control"
placeholder="duration"
value={duration}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("country_of_origin")}
type="text"
className="form-control"
placeholder="country_of_origin"
value={country_of_origin}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("director")}
type="text"
className="form-control"
placeholder="director"
value={director}
/>
</div>
<button type="submit" onClick={onSubmit} className="btn btn-success mb-2">
Add Movie
</button>
</form>
);
return (
<div>
<Navbar/>
<div className='container'style={{height:'0px'}}>
<Link to='/admin/dashboard'> <h1 className=' bg-info text-white p-4 text-decoration-none'>Admin Home</h1> </Link>
<div className='row bg-dark text-white rounded'>
<div className='col-md-8 offset-md-2'>
{successMessage()}
{addMovieForm()}
</div>
</div>
</div>
<Footer/>
</div>
)
}
export default AddMovie;
api call
This is my api request where frontend is talk with backend
import {API} from '../backend';
//add movie
export const addMovie = (userId,token,movie)=>{
return fetch(`${API}/movie/addMovie/${userId}`,{
method : "POST",
headers:{
Accept:'Application/json',
"Content-Type" : "application/json",
Authorization: `Bearer ${token}`
},
body:JSON.stringify(movie)
}).then(response => {
return response.json()
})
.catch(err => console.log(err))
}
//get all movie
export const getAllMovies = () => {
return fetch(`${API}/movies`,{
method : "GET"
})
.then(response => {
return response.json();
})
.catch(err => console.log(err))
}
//get a movie
export const getMovie = movieId =>{
return fetch(`${API}/movie/${movieId}`,{
method : "GET"
})
.then(response => {
return response.json();
})
.catch(err => console.log(err))
}
//update movie
export const updateMovie = (movieId,userId,token,movie)=>{
return fetch(`${API}/movie/${movieId}/${userId}`,{
method : "PUT",
headers:{
Accept:'Application/json',
Authorization: `Bearer ${token}`
},
body:movie
}).then(response => {
return response.json()
})
.catch(err => console.log(err))
}
//delete movie
export const deleteMovie = (movieId,userId,token)=>{
return fetch(`${API}/movie/${movieId}/${userId}`,{
method : "DELETE",
headers:{
Accept:'Application/json',
Authorization: `Bearer ${token}`
}
}).then(response => {
return response.json()
})
.catch(err => console.log(err))
}
##backend##
addmovie.js
This is backend addmovie logic where error occure
exports.addMovie = (req, res) => {
let form = new formidable.IncomingForm(); // declare a form
form.keepExtensions = true;
form.parse(req, (err, fields, file) => { //parse the form like err,fields,file
if (err) {
return res.status(400).json({
error: "Problem with image"
});
}
//destructure the field
const {movie_name,actor,country_of_origin,duration,director } = fields;
if (!movie_name || !actor || !country_of_origin || !duration || !director)
{
return res.status(400).json({
error: "please include all fields"
})
}
let movie = new Movie(fields);
//handle file here
if (file.photo) {
if (file.photo.size > 300000) {
return res.status(400).json({
error: "file size to big!"
})
}
movie.photo.data = fs.readFileSync(file.photo.path)
movie.photo.contentType = file.photo.type;
}
//save to the database
movie.save((err, movie) => {
if (err) {
res.status(400).json({
error: "saving movie in database failed"
})
}
res.json(movie);
})
})
}

Uncaught (in promise) SyntaxError: Unexpected token r in JSON at position 0

I am really a beginner in react and express. I did everything exactly as same as login, but in register it gives me "Uncaught (in promise) SyntaxError: Unexpected token r in JSON at position 0" this error.
This is my react code:
import React, { Component } from 'react';
class Register extends Component {
constructor(props) {
super(props)
this.state = {
email: '',
password: '',
name: ''
}
}
onEmailChange = (event) => {
this.setState({email: event.target.value})
}
onPasswordChange = (event) => {
this.setState({password: event.target.value})
}
onNameChange = (event) => {
this.setState({name: event.target.value})
}
onSubmitRegister = () => {
fetch('http://localhost:3101/register', {
method: "post",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
name: this.state.name,
email: this.state.email,
password: this.state.password
})
})
.then(response => response.json())
.then(data => {
console.log(data)
})
console.log('in')
}
render( props ) {
return (
<article className="br3 ba b--black-10 mv4 w-100 w-50-m w-25-l mw6 shadow-5 center">
<main className="pa4 black-80">
<div className="measure">
<fieldset id="sign_up" className="ba b--transparent ph0 mh0">
<legend className="f4 fw6 ph0 mh0">Register</legend>
<div className="mt3">
<label className="db fw6 lh-copy f6" htmlfor="name">Email</label>
<input onChange = {this.onEmailChange} className="pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100" type="text" name="name" id="name" />
</div>
<div className="mt3">
<label className="db fw6 lh-copy f6" htmlfor="name">Name</label>
<input onChange = {this.onNameChange} className="pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100" type="email" name="email-address" id="email-address" />
</div>
<div className="mv3">
<label className="db fw6 lh-copy f6" htmlfor="password">Password</label>
<input onChange = {this.onPasswordChange} className="b pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100" type="password" name="password" id="password" />
</div>
</fieldset>
<div className="">
<input onClick = {this.onSubmitRegister} className="b ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib" type="submit" value="Register" />
</div>
</div>
</main>
</article>
)
}
}
export default Register;
This is the server:
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(bodyParser.json());
app.use(cors());
const database = {
users: [
{
id: '123',
name: 'Zihan',
email: 'zihan#gmail.com',
password: 'booga',
entries: 0,
joined: new Date()
},
{
id: '124',
name: 'Shakib',
email: 'shakib#gmail.com',
password: 'choto',
entries: 0,
joined: new Date()
}
]
}
app.get('/', (req,res) => {
res.send(database.users);
})
app.post('/signin', (req,res) => {
if ( req.body.email === database.users[0].email && req.body.password === database.users[0].password ){
res.json('success');
}
else{
res.status(400).json('error logging in');
}
})
app.post('/register', (req,res) => {
const {name, email, password} = req.body;
database.users.push({
id: '134',
name: name,
email: email,
password: password,
entries: 0,
joined: new Date()
})
res.send('registrition sussessful')
})
app.get('/profile/:id', (req, res) => {
const { id } = req.params;
let found = false;
database.users.forEach(user => {
if(user.id === id) {
found = true;
return res.send(user);
}
})
if(!found){
res.status(404).json('not found')
}
})
app.put('/image', (req,res) => {
const { id } = req.body;
let found = false;
database.users.forEach(user => {
if(user.id === id) {
found = true;
user.entries++
return res.json(user.entries);
}
})
if(!found){
res.status(404).json('not found')
}
})
app.listen(3101, () => {
console.log('app is runing')
})
This is the console tab:
The error
This is the network tab:
This is response and it seems ok
As you can see my response is ok and I tested it by postman I am getting the registered user but react is throwing me the error.
Change this
res.send('registrition sussessful')
To this
res.json('registrition sussessful')
Or even better
res.status(200).send({message: "registration successful" })

Redirect to profile after login

I am doing google auth with passport and
I wanna redirect to the profile after successfully logged in.
The problem is my method of this.props.history.push('/profile') dont work.
By the way, it's from my router that I need to redirect the user to profile.
All the authentication is in the route.
Here is my code any suggestions?
The if (user) {} is true my only problem is on how to redirect the user.
Route:
const Strategy = require('passport-local').Strategy
const mongoose = require('mongoose')
const GoogleUser = require('../models/google');
const GoogleAuth = new Strategy(
{ passReqToCallback: true, usernameField: "email", passwordField: "id" },
function(req, email, id, done) {
GoogleUser.findOne({ email: req.body.email })
.lean()
.exec((err, user) => {
if (err) {
return done(err, null);
}
if (!user) {
let newUser = new GoogleUser({
email: req.body.email,
id: req.body.id,
name: req.body.name,
token: req.body.token,
image: req.body.image
});
newUser.save((error, inserted) => {
if (error) {
return done(error, null);
}
return done(null, inserted);
});
}
if (user) {
this.props.history.push("/profile");
}
});
}
);
module.exports = GoogleAuth;
Here is the React code if needed:
import React, { Component } from 'react';
import axios from "axios";
import {Redirect} from "react-router-dom"
import styles from '../styles/loginsignup.css'
import logo from '../img/nowyourguest.png'
import 'bootstrap/dist/css/bootstrap.min.css'
import 'jquery/dist/jquery.min.js'
import 'bootstrap/dist/js/bootstrap.min.js'
export default class Login extends Component {
componentDidMount() {
this.googleSDK();
console.log('sfsfd');
}
prepareLoginButton = () => {
console.log(this.refs.googleLoginBtn);
this.auth2.attachClickHandler(this.refs.googleLoginBtn, {},
(googleUser) => {
let profile = googleUser.getBasicProfile();
const email = profile.getEmail()
const id = profile.getId()
const name = profile.getName()
const token = googleUser.getAuthResponse().id_token
const image = profile.getImageUrl()
axios({
url: "/authentication/google",
method: "POST",
data: {
email,
id,
name,
token,
image
}
})
.then(response => {
const isAuthenticated = response.data.isAuthenticated
window.localStorage.setItem('isAuthenticated', isAuthenticated);
this.props.history.push('/profile')
})
.catch(error =>{
this.setState({
errorMessage:error.response.data.message
})
})
})
}
googleSDK = () => {
window['googleSDKLoaded'] = () => {
window['gapi'].load('auth2', () => {
this.auth2 = window['gapi'].auth2.init({
client_id: 'clientID',
cookiepolicy: 'single_host_origin',
scope: 'profile email'
});
this.prepareLoginButton();
});
}
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "https://apis.google.com/js/platform.js?onload=googleSDKLoaded";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'google-jssdk'));
}
state = {
email: '',
password: ''
};
handleSubmit = event => {
event.preventDefault();
const {email, password } = this.state;
axios({
url: "/authentication/signin",
method: "POST",
data: {
email,
password
}
})
.then(response => {
const isAuthenticated = response.data.isAuthenticated
window.localStorage.setItem('isAuthenticated', isAuthenticated);
this.props.history.push('/profile')
})
.catch(error =>{
this.setState({
errorMessage:error.response.data.message
})
})
};
handleChange = event => {
const {name, value} = event.target;
this.setState({
[name]:value
})
}
render() {
const isAuthenticated = window.localStorage.getItem('isAuthenticated');
if (isAuthenticated) {
return <Redirect to='/profile' />
}
return(
<div>
<div>
<nav className="navbar navbar-expand-lg navbar-light bg-info sticky-top" id="shadow">
<a className="navbar-brand text-warning" href="/">NowYourGuest</a>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon" />
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent" >
<ul className="navbar-nav mr-auto">
<li className="nav-item">
<a className="nav-link text-white" href="/add-your-accomodation">Add your accomodation</a>
</li>
<li className="nav-item active">
<a className="nav-link" href="/login">Login<span className="sr-only">(current)</span></a>
</li>
<li className="nav-item">
<a className="nav-link text-white" href="/signup">Signup</a>
</li>
</ul>
</div>
<form className="form-inline my-2 my-lg-0">
<input className="form-control mr-sm-2" type="search" placeholder="Search for accomodation" aria-label="Search" />
</form>
</nav>
</div>
<div className="container">
<div className="card card-container">
<center><img id="profile-img" className="profile-img" src={logo} /></center>
<p id="profile-name" className="profile-name-card" />
<form onSubmit={this.handleSubmit} className="form-signin">
<span id="reauth-email" className="reauth-email" />
<input type="text" id="inputEmail" className="form-control" name="email" onChange={this.handleChange} placeholder="Email address" required autofocus />
<input type="password" id="inputPassword" className="form-control" name="password" onChange={this.handleChange} placeholder="Password" required />
<center><p style={{color: 'red'}}>{this.state.errorMessage}</p></center>
<button className="btn btn-lg btn-primary btn-block btn-signin" type="submit">Sign in</button>
</form>
<button className="loginBtn loginBtn--google" ref="googleLoginBtn">Login with Google</button>
<a href="#" className="forgot-password">
Forgot the password?
</a>
</div>
</div>
</div>
)
}
}
module.exports = Login;
you need to use "withRouter" from "react-router-dom".
All you need to do is import withRouter and wrap your component at export:
import { withRouter } from "react-router-dom";
//.
//.
//.
export default class (withRouter(Login))
You can also use Redirect component from "react-router-dom" and return it instead
import { Redirect } from "react-router-dom";
// Your code
render() {
if (User) {
return <Redirect to={"/route"} />
}
return(
// If user is not logged...
)
}
I just made 2 different routes in one login and one register.
And it perfectly works.

Cannot POST /Admin

I was connecting react with my api in node js, but when connecting to the login the only thing that appears is "Cannot POST / Admin"
I have used the Postman and it seems that the back part works because the token returns, but I think there is some problem in the connection between the two.
I am working on react, nodejs, redux and mongodb
interface IProps {}
interface IPropsGlobal {
setToken: (t: string) => void;
setName: (u: string) => void;
}
const Login: React.FC<IProps & IPropsGlobal> = props => {
const [username, setUsername] = React.useState("");
const [password, setPassword] = React.useState("");
const [error, setError] = React.useState("");
const updateUsername = (event: React.ChangeEvent<HTMLInputElement>) => {
setUsername(event.target.value);
setError("");
};
const updatePassword = (event: React.ChangeEvent<HTMLInputElement>) => {
setPassword(event.target.value);
setError("");
};
const signIn = () => {
fetch("http://localhost:3006/api/auth", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
username: username,
password: password
})
})
.then(response => {
if (response.ok) {
response
.text()
.then(token => {
console.log(token);
props.setToken(token);
props.setName(username);
});
} else {
setError("Usuario o Contraseña incorrectos");
}
})
.catch(err => {
setError("Usuario o Contraseña incorrectos.");
});
};
return (
<div>
<div className="section"></div>
<h5 className="indigo-text">Please, login into your account</h5>
<div className="section"></div>
<div className="container">
<div className="z-depth-1 grey lighten-4 row er" >
<form className="col s12" method="post">
<div className='row'>
<div className='col s12'>
</div>
</div>
<div className='row'>
<div className='input-field col s12'>
<input className='validate' name='email' id='email' value={username}
onChange={updateUsername}/>
<label >Enter your email</label>
</div>
</div>
<div className='row'>
<div className='input-field col s12'>
<input className='validate' type='password' name='password' id='password' value={password}
onChange={updatePassword} />
<label >Enter your password</label>
</div>
<label >
<a className='pink-text' href='#!'><b>Forgot Password?</b></a>
</label>
</div>
<br />
<div className='row'>
<button type='submit' name='btn_login' className='col s12 btn btn-large waves-effect indigo'
onClick={signIn}>Login</button>
</div>
</form>
</div>
</div>
Create account
</div>
);
};
const mapDispatchToProps = {
setToken: actions.setToken,
setName: actions.setName
};
export default connect(
null,
mapDispatchToProps
)(Login);
Postman returns the token
The api console shows me:
POST /api/auth - - ms - -
Connected successfully to server
In the Web page
Failed to load resource: the server responded with a status of 404 (Not Found)
I have used this code or a similar one before in other projects but I do not understand what happened to me this time
const md5 = require('md5');
// Connection URL
const mongoUrl = 'mongodb://localhost:27017';
// Database Name
const mongoDBName = 'ArdalesTur';
/* GET users listing. */
router.get('/', (req, res) => {
res.send('respond with a resource');
});
const secret = 'mysecret';
// para interactuar con la base de datos
router.post('/auth', (req, res) => {
mongo.MongoClient.connect(mongoUrl, (err, client) => {
assert.equal(null, err);
console.log('Connected successfully to server');
const db = client.db(mongoDBName);
const query = db.collection('Admin').find({
username: req.body.username,
password: md5(req.body.password),
});
query.toArray().then((documents) => {
if (documents.length > 0) {
const token = jwt.sign(
{
_id: documents[0]._id,
username: documents[0].username
},
secret,
// {
// expiresIn: 86400
// }
);
res.send(token);
} else {
res.status(400).send('Invalid credentials');
}
});
client.close();
});
});
here you have the api

Resources