I am new to react and I task is to remove the Jwt token from local storage when the user log out. I have tried on many methods but I failed to do so. Anyone can help? Thanks in advance :)
The code below is my code
my navbar code:
const Sidebar = ({auth: {isAuthenticated}},logoutUser) => {
const authlinks=(
<ul>
<li>
<Link to="/profiles">Developers</Link>
</li>
<li>
<Link to="/posts">Posts</Link>
</li>
<li>
<Link to="/dashboard">
<i className="fas fa-user" />{' '}
<span className="hide-sm">Dashboard</span>
</Link>
</li>
<li>
<Link to ="/home">
<a onClick={logoutUser}>
<i className="fas fa-sign-out-alt" />{' '}
<span className="hide-sm">Logout</span>
</a>
</Link>
</li>
</ul>
);
const guestLinks = (
<ul>
<li>
<Link to="/profiles">Developers</Link>
</li>
<li>
<Link to="/register">Register</Link>
</li>
<li>
<Link to="/login">Login</Link>
</li>
</ul>
);
return (
<Navbar bg="dark" expand="lg" variant="dark">
<Fragment>{isAuthenticated ? authlinks :
guestLinks}</Fragment>
</Navbar>
);
};
Sidebar.propTypes={
logoutUser: propTypes.func.isRequired,
auth: propTypes.object.isRequired
}
const mapStateToProps = (state)=>({
auth: state.auth
});
export default connect(mapStateToProps, {logoutUser})
(withRouter(Sidebar));
the code below is my remove token function:
this function is to remove the token from the local storage
export const logoutUser = () => dispatch => {
localStorage.removeItem("jwtToken");
setAuthToken(false);
dispatch(setCurrentUser({}));
}
Importantly, your Sidebar component should only take one argument (props) but right now you have it taking two arguments. You can fix this by fixing how you destructure the props:
const Sidebar = ({auth: {isAuthenticated},logoutUser}) => {
// logoutUser should work now
}
Related
i have looked up every relating posts for 8hours but still cant solve it
{comments.map((c) => {
console.log(c)
return(
<div className="col-lg-12" key={c._id}>
<div className="testi-item">
<div className="testi-comment">
<p>
<i className="fa fa-quote-left" />
{c.message}
<i className="fa fa-quote-right" />
</p>
<ul className="stars list-unstyled">
<li>
<i className="fa fa-star" />
</li>
<li>
<i className="fa fa-star" />
</li>
<li>
<i className="fa fa-star" />
</li>
<li>
<i className="fa fa-star-half-alt" />
</li>
<li>
<i className="fa fa-star" />
</li>
</ul>
</div>
<div className="client-info">
<h5>{c.companyName}</h5>
<p>{c.ip}</p>
</div>
</div>
</div>
states
const [comments, setComments] = useState([]);
const getComments = async function () {
try {
const response = await axios.get("/comment");
console.log(response);
setComments(response.data.comments);
} catch (error) {
console.error(error);
}
};
smaple object
{ companyName: "asd" ip: "112.214.38.68" message: "asd" _id: "6162fb4c06b4541fa2420f5c" }
enter image description here
Uncaught Error: Objects are not valid as a React child (found: object with keys {_id, companyName, message, ip}). If you meant to render a collection of children, use an array instead.
please help
complete code
import React, { useState } from "react";
import OwlCarousel from "react-owl-carousel";
import "owl.carousel/dist/assets/owl.carousel.css";
import "owl.carousel/dist/assets/owl.theme.default.css";
import ScreenHeading from "../../utilities/ScreenHeading/ScreenHeading";
import ScrollService from "../../utilities/ScrollService";
import Animations from "../../utilities/Animations";
import "./Testimonial.css";
import shape from "../../../src/img/Testimonial/shape-bg.png";
import Comment from "../CommentComponent/Comment";
import axios from "axios";
import lady from "../../../src/img/Testimonial/lady.png";
import mike from "../../../src/img/Testimonial/mike.png";
import man from "../../../src/img/Testimonial/man.png";
export default function Testimonial(props) {
const [comments, setComments] = useState([]);
const getComments = async function () {
try {
const response = await axios.get("/comment");
console.log(response);
setComments(response.data.comments);
} catch (error) {
console.error(error);
}
};
let fadeInScreenHandler = (screen) => {
if (screen.fadeInScreen !== props.id) return;
Animations.animations.fadeInScreen(props.id);
getComments();
};
const fadeInSubscription =
ScrollService.currentScreenFadeIn.subscribe(fadeInScreenHandler);
const options = {
loop: true,
margin: 0,
nav: true,
animateIn: "bounceInRight",
animateOut: "bounceOutRight",
dots: true,
autoplay: true,
smartSpeed: 1000,
responsive: {
0: {
items: 1,
},
768: {
items: 1,
},
1000: {
items: 3,
},
},
};
return (
<div>
<ScreenHeading title={"Valuable Comments"} subHeading={"방명록 리스트"} />
<section className="testimonial-section fade-in" id={props.id || ""}>
<div className="container">
<div className="row">
<OwlCarousel
className="owl-carousel"
id="testimonial-carousel"
{...options}
>
{comments}
{!comments ? (
<div>non</div>
) : (
<div>
{comments.map((c) => {
console.log(c)
return (
<div className="col-lg-12" key={c._id}>
<div className="testi-item">
<div className="testi-comment">
<p>
<i className="fa fa-quote-left" />
{c.message}
<i className="fa fa-quote-right" />
</p>
<ul className="stars list-unstyled">
<li>
<i className="fa fa-star" />
</li>
<li>
<i className="fa fa-star" />
</li>
<li>
<i className="fa fa-star" />
</li>
<li>
<i className="fa fa-star-half-alt" />
</li>
<li>
<i className="fa fa-star" />
</li>
</ul>
</div>
<div className="client-info">
<h5>{c.companyName}</h5>
<p>{c.ip}</p>
</div>
</div>
</div>
);
})}
</div>
)}
</OwlCarousel>
</div>
</div>
</section>
<div className="footer-image">
<img src={shape} alt="not responding" />
</div>
</div>
);
}
You’ve embedded a bare {comments} in your render function right before the ternary; comments is an object and can’t be dropped into the DOM raw, just like the error message is telling you.
Remove that line and it should be fine.
The issue is here:
{comments}
You should remove this line.
If you woule like to see the comments you should do:
{JSON.stringify(comments)}
I am building a nav bar with a logout button. Ideally, I would like the user to be redirected back to homepage when the log out button is being clicked. However, I am getting an error: Unhandled Rejection (TypeError): undefined has no properties when the logout button is being clicked.
Can someone kindly advice?
import React, { Component, useContext } from 'react';
import { Link, Redirect } from 'react-router-dom';
import logo from '../favicon.png';
import AuthService from '../Services/AuthServices';
import { AuthContext } from '../AuthContext';
const Navbar = props => {
const { isAuthenticated, user, setIsAuthenticated, setUser } = useContext(AuthContext);
const onClickLogoutHandler = () => {
AuthService.logout().then(data => {
if (data.success) {
setUser(data.user);
setIsAuthenticated(false);
this.props.history.push('/') }
});
}
const unauthenticatedNavBar = () => {
return (
<>
<nav className="navbar navbar-expand-sm navbar-dark bg-dark px-sm-5">
<Link to='/'>
<img src={logo} alt="store"
className='navbar-brand' />
</Link>
<ul className='navbar-nav align-item-center'>
<li className="nav-item ml=5">
<Link to="/" className="nav-link">
PRODUCTS
</Link>
</li>
</ul>
<div className="input-group">
<div className="input-group-prepend">
<div className="input-group-text" id="btnGroupAddon">#</div>
</div>
<input type="text" className="form-control" placeholder="Input group example" aria-label="Input group example" aria-describedby="btnGroupAddon" />
</div>
<ul className='navbar-nav align-item-center'>
<li className="nav-item ml-5">
<Link to="/signup" className="nav-link">
Sign Up
</Link>
</li>
<li className="nav-item ml-5">
<Link to="/login" className="nav-link">
Log In
</Link>
</li>
</ul>
<Link to='/sell' className="ml-5">
<button type='button' className="btn btn-danger">SELL</button>
</Link>
</nav>
</>
)
}
const authenticatedNavBar = () => {
return (
<>
<nav className="navbar navbar-expand-sm navbar-dark bg-dark px-sm-5">
<Link to='/'>
<img src={logo} alt="store"
className='navbar-brand' />
</Link>
<ul className='navbar-nav align-item-center'>
<li className="nav-item ml=5">
<Link to="/" className="nav-link">
PRODUCTS
</Link>
</li>
</ul>
<div className="input-group">
<div className="input-group-prepend">
<div className="input-group-text" id="btnGroupAddon">#</div>
</div>
<input type="text" className="form-control" placeholder="Input group example" aria-label="Input group example" aria-describedby="btnGroupAddon" />
</div>
<ul className='navbar-nav align-item-center'>
<li className="nav-item ml-5">
<Link to="/profile" className="nav-link">
{user.username}
</Link>
</li>
<Link to='/sell' className="ml-5">
<button type='button' className="btn btn-danger">SELL</button>
</Link>
<button type="button"
className="btn btn-link nav-item nav-link"
onClick={onClickLogoutHandler}>Logout</button>
</ul>
</nav>
</>
)
}
return (
<>
{!isAuthenticated ? unauthenticatedNavBar() : authenticatedNavBar()}
</>
)
}
export default Navbar;
I want to get image urls by scraping data by cheerio from a slider but can able to do this tried a lot but can found a solution here is my code below
const retURL = a.find('.gallery-carousel').find('img').attr('src')
.map(function(){
let image= $(this).attr('src');
console.log(image, 'nnnnknknkn')
})
const retURL = $('div.carousel').attr('img')
const retURL = $('gallery-carousel__image-touchable').text()
var listItems = $(".gallery-carousel ul li");
listItems.each(function(idx, li) {
let image= $(li).find('img').attr('src');
console.log(image);
// and the rest of your code
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="gallery-carousel">
<ul>
<li class="slide selected">
<button><img src="https://i.stack.imgur.com/rC97H.png" alt="hello" /> </button>
</li>
<li class="slide">
<button><img src="https://i.stack.imgur.com/1.png" alt="hello" /> </button>
</li>
<li class="slide">
<button><img src="https://i.stack.imgur.com/2.png" alt="hello" /> </button>
</li>
</ul>
</div>
Im having problems to make a post request to upload a file from angular to the server in nodejs.
the method is fine from the server in nodejs when i test it in postman, so I supose that the issue is in the client cors. I dont know if there is a special configuration i need to make in the express.cors?
Lado del servidor
server.js
require('./config/config');
const express = require('express');
const mongoose = require('mongoose');
var cors = require('cors');
const app = express();
app.use(cors())
const bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json())
app.use(require('./routes/index'));
mongoose.connect('mongodb://localhost:27017/colegios', (err, res) => {
if (err) throw err;
console.log('BDD Conectada exitosamente!!!');
});
app.listen(process.env.PORT, () => {
console.log('Escuchando puerto: ', process.env.PORT);
});
autenticado.component.ts
import { Component, OnInit } from '#angular/core';
import { FileSelectDirective, FileUploader } from 'ng2-file-upload';
import { UsuarioService } from '../services/usuario.service';
import { CarreraService } from '../services/carrera.service';
import { Carrera } from '../models/carrera.model';
import { Observable } from 'rxjs';
import { HttpClient } from '#angular/common/http';
const uri = 'http://localhost:3000/upload3/';
#Component({
selector: 'app-autenticado',
templateUrl: './autenticado.component.html',
styleUrls: ['./autenticado.component.css']
})
export class AutenticadoComponent implements OnInit {
public title: string;
public identity;
carreras: Carrera[] = [];
attachmentList: any = [];
uploader: FileUploader;
constructor(public usuarioServ: UsuarioService, public carreraServ: CarreraService, public http: HttpClient) {
this.identity = usuarioServ.getIdentity();
this.uploader = new FileUploader({ url: uri + this.identity._id });
console.log(uri + this.identity._id);
this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
console.log(response);
this.attachmentList.push(response);
};
}
ngOnInit() {
this.title = 'Te has logueado exitosamente!';
/* this.obtenerCarreras();
console.log(this.carreras); */
}
obtenerCarreras() {
try {
const getCarreras = this.carreraServ.getCarreras();
getCarreras.subscribe((resp: any) => {
console.log(resp);
for (let index = 0; index < resp.length; index++) {
this.carreras[index] = resp[index];
}
});
} catch (error) {
console.log(error);
}
}
}
autenticado.component.html
<div class="navigation col-lg-12">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
{{ title }}
</div>
<ul class="nav navbar navbar-nav navbar-right">
<li>
<a [routerLink]="['/login']" [routerLinkActive]="['active']"> Login </a>
<span class="glyphicon glyphicon-log-in"> </span>
</li>
</ul>
<!--
=========================================================
Panel de Alumno solicitante de citas
=========================================================
-->
<ul class="nav navbar-nav" *ngIf="identity.role === 'ALUMNO_ROLE'">
<li>
<span class="glyphicon glyphicon-home"> </span>
<a [routerLink]="['/home']" [routerLinkActive]="['active']"> Inicio </a>
</li>
</ul>
<div class="container-fluid">
<div class="row header-section">
<span>Selecciona la carrera a la que haras la solicitud</span>
</div>
<div class="row">
<div id="seccioncarreras">
<select id="carreras">
<option value=""></option>
<option *ngFor="let carrera of carreras" [value]="carrera._id"> {{ carrera.nombre }} </option>
</select>
</div>
<div class="col-md-2"></div>
<div class="col-md-8">
<div class="row card">
<div class="col-sm-12">
<h4>Upload Section</h4>
<div id="fileSelector">
<input type="file" name="fileUpload" id="fileUpload" ng2FileSelect [uploader]="uploader">
</div>
<div>
<div class="row uploadList" *ngFor="let item of uploader.queue">
<div class="col-sm-4">
{{ item.file.name }}
</div>
<div class="col-sm-4">
<div class="progress">
<div class="progress-bar bg-success" [ngStyle]="{'width':item.progress+'%'}"></div>
</div>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-dark" (click)="item.upload()">Upload</button>
<button type="button" class="btn btn-danger">Cancel</button>
</div>
</div>
</div>
<div class="row">
<button type="button" class="btn btn-primary">Upload All</button>
</div>
</div>
</div>
</div>
<div class="col-md-2"></div>
</div>
</div>
<!--
=========================================================
Panel de administrador del colegio
=========================================================
-->
<ul class="nav navbar-nav" *ngIf="identity.role === 'ADMIN_ROLE'">
<li>
<span class="glyphicon glyphicon-home"> </span>
<a [routerLink]="['/home']" [routerLinkActive]="['active']"> Inicio Maestro </a>
</li>
<li>
<a [routerLink]="['/registrar']" [routerLinkActive]="['active']"> otro </a>
<span class="glyphicon glyphicon-user"> </span>
</li>
<li>
<a [routerLink]="['/registro-curso']" [routerLinkActive]="['active']"> Maestro </a>
<span class="glyphicon glyphicon-plus"> </span>
</li>
</ul>
<ul class="nav navbar navbar-right" *ngIf="identity">
<li class="dropdown open">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
{{ identity.nombre }} <span class="caret"> </span> </a>
<ul class="dropdown-menu">
<li>
<a href="#">
<span class="glyphicon glyphicon-log-out"></span>
Cerrar Sesion
</a>
</li>
</ul>
</li>
</ul>
</div>
</nav>
</div>
you should remove this middleware:
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
because I saw that you added cors express middleware module, and it did handled the Access-Control-Allow-Origin issue already. you should have a look on its document if need any customization.
Cors request cannot server '*' for Access-Control-Allow-Origin if the request contains any authorization.
You have to answer the current asking host, so localhost:4020 in your case.
If you really wants to allows *, just answer with that
res.header("Access-Control-Allow-Origin", req.headers['Host'] );
But in any case, do not use both express.cors and your own middleware.
Using requirejs, I can use simple routes like /register, but I always get an error when I try a nested route like /register/1 or something.
This works (where the route is just /register):
layout.js
define(['require', 'axios'], (require, axios) => {
const layout = `
<div class="container">
<div class="row">
<div class="header clearfix">
<nav style="padding-top: 10px">
<ul class="nav nav-pills pull-left">
<li role="presentation">
<h3>My App</h3>
</li>
</ul>
<ul class="nav nav-pills pull-right">
<li role="presentation">Login</li>
<li role="presentation">Register</li>
</ul>
</nav>
</div>
</div>
</div>
`;
if (window.location.pathname === '/') {
window.location.pathname = '/home'
}
axios.defaults.headers.common['authorization'] = Cookies.get('token')
return layout
})
register.js
define(['layout'], layout => {
if (window.location.pathname === '/register') {
console.log("Got it") // This works since the route is just '/register'
}
})
This does not work (where the route is /register/1):
layout.js
define(['require', 'axios'], (require, axios) => {
const layout = `
<div class="container">
<div class="row">
<div class="header clearfix">
<nav style="padding-top: 10px">
<ul class="nav nav-pills pull-left">
<li role="presentation">
<h3>My App</h3>
</li>
</ul>
<ul class="nav nav-pills pull-right">
<li role="presentation">Login</li>
<li role="presentation">Register</li>
</ul>
</nav>
</div>
</div>
</div>
`;
if (window.location.pathname === '/') {
window.location.pathname = '/home'
}
axios.defaults.headers.common['authorization'] = Cookies.get('token')
return layout
})
register.js
define(['layout'], layout => {
if (window.location.pathname === '/register/1') {
console.log("Got it") // Error
}
})
index.html
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<link
rel="stylesheet"
type="text/css"
href="/stylesheets/style.css">
<link
rel="stylesheet"
type="text/css"
href="/stylesheets/registration.css">
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
crossorigin="anonymous">
<script
type="text/javascript"
src="/javascripts/styles/js.cookie.js">
</script>
<script data-main="config" src="require.js"></script>
<script>require(['config'])</script>
</head>
<body>
<div id="my-app"></div>
</body>
</html>
config.js
requirejs.config({
baseUrl: 'javascripts/views',
paths: {
allConversations: 'allConversations',
conversation: 'conversation',
home: 'home',
layout: 'layout',
loginView: 'login',
login: '../scripts/login',
logoutHandler: '../scripts/logout',
memberProfile: 'memberProfile',
profile: 'profile',
register: 'register',
conversationCount: 'conversationCount',
nav: 'nav',
axios: '//unpkg.com/axios/dist/axios.min',
jquery: [
'//code.jquery.com/jquery-3.3.1.min',
'//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min'
],
bootstrap: ['//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min'],
fontAwesome: ['//use.fontawesome.com/7973784de3'],
},
})
require([
'home',
'layout',
'loginView',
'login',
'logoutHandler',
'nav',
'register'
])
How do I use nested URL routes with requirejs?
First problem. You are loading config module twice. data-main attribute specifies what modules should be loaded after the RequireJS load. So the second line is basically a duplicate of this
<script data-main="config" src="require.js"></script>
<script>require(['config'])</script>
Please replace this with just
<script data-main="config" src="require.js"></script>
Second problem, you have syntax error in layout.js. Your syntax looks like JSX, not regular JavaScript. Please amend this or use RequireJS JSX files loader plugin -> https://github.com/philix/jsx-requirejs-plugin
Can you please show use you config module?
Cheers.