Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)

I am getting this error

Mainsection.js:27 Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)

Here is my mainsection.js file, I am using API key to iterate the data, I am still not getting the cause of the error. First I had made an array whose name was info and stored all the data in it and then iterated it, Now after using fetchapi, I deleted that array as it was of no use. I don’t know whether it was meant to delete or not.

import React, { Component } from 'react'
import Card from './Card'

export default class Mainsection extends Component {

    constructor() {
        super();
        this.state = {
            info: this.info
        }
    }
async componentDidMount(){
    let Url="https://randomuser.me/api/?inc=gender,name,nat,location,picture,email&results=";
    let data= await fetch(Url);
    let parsedData= await data.json()
    console.log(parsedData);
    this.setState({
        info : parsedData.info
    })

}

    render() {
        return (
            <div>
                <div className="container mt-5">
                    <div className="row">
                        {this.state.info.map((element) => {
                            return <div className="col-md-4">
                                <Card key={element.email} name={element.name} location={element.location} gender={element.gender} imageUrl={element.picture.medium} />
                            </div>
                        })}

                    </div>
                </div>
            </div>
        )
    }
}

And here is my card.js file

import React, { Component } from 'react'

export default class Card extends Component {
    render() {
        let {name, location, gender, imageUrl}=this.props
        return (
            <div>
                 <div className="card" style={{ width: "18rem" }}>
            <img src={imageUrl} className="card-img-top" alt="..." />
            <div className="card-body">
                <h5 className="card-title">{name}</h5>
                <p className="card-text">{location}</p>
                <p className="card-text">{gender}</p>
                <a href="/" className="btn btn-primary">Go somewhere</a>
            </div>
        </div>
            </div>
        )
    }
}

Please let me I should provide more details

404 Page without redirect using .htaccess

I want to setup 404 & 403 page using .htaccess but without the redirection.

My Code :

ErrorDocument 404 404error.php
ErrorDocument 403 403error.php

The code work fine but it redirect example.com/any-non-existed-page to example.com/404error.php but i want, if someone visited any not found page like example.com/any-non-existed-page then it should show the content of 404error.php without changing/redirecting the link. means the url remain same example.com/any-non-existed-page but the content are displayed from 404error.php .

Please help!!

How to access html element in php

I want to display message to user in html page that the email or password is wrong when he put wrong data.
I have

<small id="messages" class="text-danger"></small>

and in the php file:

if(!empty($row)){
        // checking password
        // unhasing password
        if(password_verify($password, $row['password'])){
            //when user correctly log in set user id
            session_start();
            $_SESSION['userID'] = $row['userID'];   
            header('location: user-profile.php');
            exit();
        } else {
            echo "You are not a member";
        }
    } else {
        echo "Please fill out!";
        
    }

and I want to echo ‘ Your are not a member’ actually show up in the small tag if the condition is correct. I know how to do that in js, but can I put js code in php? What is the correct way to actually done that?

React Dependency Tree Issue

Can anyone tell me what’s incorrect here? I am trying to install the mui search bar component.

npm i --save material-ui-search-bar

However I do receive the following:

PS Z:WebDevApplyWithinfrontend> npm i --save material-ui-search-bar
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"^17.0.2" from the root project
npm ERR!   peer react@"^16.8.0 || ^17.0.0" from @material-ui/[email protected]
npm ERR!   node_modules/@material-ui/core
npm ERR!     peer @material-ui/core@"^4.0.0" from [email protected]
npm ERR!     node_modules/material-ui-search-bar
npm ERR!       material-ui-search-bar@"*" from the root project
npm ERR!     peer @material-ui/core@"^4.0.0" from @material-ui/[email protected]
npm ERR!     node_modules/@material-ui/icons
npm ERR!       @material-ui/icons@"^4.11.2" from the root project
npm ERR!       1 more (material-ui-search-bar)
npm ERR!   2 more (react-dom, @material-ui/icons)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.8.0" from [email protected]
npm ERR! node_modules/material-ui-search-bar
npm ERR!   material-ui-search-bar@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

My package.json is:

{
  "name": "new",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.7.0",
    "@emotion/styled": "^11.6.0",
    "@fontsource/roboto": "^4.5.1",
    "@material-ui/icons": "^4.11.2",
    "@mui/icons-material": "^5.2.4",
    "@mui/material": "^5.2.3",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "framer-motion": "^4.1.17",
    "gsap": "^3.9.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-intersection-observer": "^8.33.1",
    "react-scripts": "4.0.3",
    "react-typewriter-effect": "^1.1.0",
    "styled-components": "^5.3.3",
    "typewriter-effect": "^2.18.2",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Does anyone have a clue here?

Cant access express session variable in other routes

require('dotenv').config();
const express = require('express');
const app = express();
const cors = require('cors');
const mongoose = require('mongoose');
const User = require('./model/user.model');
const nodemailer = require("nodemailer");
const generate = require("generate-password");
const session = require('express-session');

const MongoStore = require("connect-mongo");

const connection = mongoose.connect("mongodb://localhost:27017/billsplitDB",{useNewUrlParser: true, useUnifiedTopology: true});

app.use(cors({
    credentials: true,
    origin: true,
}));


app.use(express.json());
app.use(express.urlencoded());

const oneDay = 1000 * 60 * 60 * 24;

app.use(session({
    secret: process.env.SESSION_SECRET,
    saveUninitialized:true,
    store: MongoStore.create({ mongoUrl: "mongodb://localhost:27017/billsplitDB"}),
    cookie: { maxAge: oneDay },
    resave: false 
}));

let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      type: 'OAuth2',
      user: process.env.MAIL_USERNAME,
      pass: process.env.MAIL_PASSWORD,
      clientId: process.env.OAUTH_CLIENTID,
      clientSecret: process.env.OAUTH_CLIENT_SECRET,
      refreshToken: process.env.OAUTH_REFRESH_TOKEN
    }
  });

  app.post("/",(req,res)=>{
      var passwords = "";
      var dbPassword = "";
      while(passwords === dbPassword){
          passwords = generate.generate({
              numbers:true,
          });
          console.log(passwords);
          User.findOne({code:passwords},(err,result)=>{
              if(!err){
                  if(result){
                      dbPassword = result.code;
                  }
              }
              else{
                  res.send({status:"not ok",reason:"database"});
              }
          });
      }
      let mailOptions = {
        from: process.env.MAIL_USERNAME,
        to: req.body.userEmail,
        subject: 'Bill Split',
        text: 'Hi your code for login this bill split account is  =  '+passwords
      };
      transporter.sendMail(mailOptions, function(err, data) {
        if (err) {
            console.log(err);
          res.status(400).send({error:"email not sent"});
        } else {
            const user  =  new User({code:passwords,billsplit:[]});
            user.save(function(err){
                if(err){
                    console.log(err);
                    res.status(400).send({error:"not saved"});
                    
                }
                else{
                    req.session.useCode = passwords;
                    console.log(req.session);
                    res.send({status:"ok",code:passwords});
                }
            });
          console.log("Email sent successfully");
        }
      });
  });

  app.post("/login",(req,res)=>{
    User.findOne({code:req.userCode},(err,result)=>{
        if(err){
            res.status(400).send({status:"not ok"});
            
        }
        else{
            if(result){
                req.session.useCode = req.userCode;
                res.send({status:"ok"});
            }
            else{
                res.send({status:"not registered"});
            }
        }
    });
  });

  app.get("/billsplit/:code",(req,res)=>{
    console.log(req.session);
    if(req.session.useCode){
    User.findOne({code:req.params.code},(err,result)=>{
        if(err){
            res.status(400).send({status:"not ok"});
            
        }
        else{
            if(result){
                res.send({status:"ok",result:result.billsplit});
            }
        }
    });
}
else{
    res.send({status:"go to login"});
}
  });

 app.post("/billsplit/:code",(req,res)=>{
     if(req.session.useCode){
     const userCode = req.params.code;
     const updatedDetails=  req.body.updatedDetails
     User.findOneAndUpdate({code:userCode},{billsplit:updatedDetails},{new:true},function(err,result){
         if(err){
            res.status(400).send({status:"not ok"});
         }
         else{
            res.send({status:"ok"});
         }
     });
     }
     else{
         res.send({status:"go to login"});
     } 
 });


app.listen(5000, () => {
    console.log("app is running on 5000 port");
  });

I am making a session variable useCoide when the user register or login and then try to access it in other routes like /billsplit. but when I console log req.session in other routes, it seems like my session variable req,useCode doesn’t even exist. how should I fix it? its a mern stack application and I am using axios to send request from client side(react). And yes I have included {withcredentials: true} in axios request already but it doesn’t help either.

How can I resolve “Response to preflight request doesn’t pass access control check” error?

I hope you had a good Christmas day.

I have been looking to solve this for 6 hours straight, but I could not.

I am getting the error:

“Access to XMLHttpRequest at ‘https://joonkim025n.korconnect.io/Rapid/cards/Rolling%20Fireball’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.”

This is the network tab:

Request Method: OPTIONS
Status Code: 403
Remote Address: xx.122.14.:443
Referrer Policy: strict-origin-when-cross-origin

Access-Control-Allow-Credentials: false
Access-Control-Allow-Headers: date,content-type,content-length,x-amzn-requestid,x-amzn-errortype,x-amz-apigw-id
Access-Control-Allow-Methods: GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: date, content-type, content-length, x-amzn-requestid, x-amzn-errortype, x-amz-apigw-id
content-length: 23
content-type: application/json
Content-Type: application/json; charset=utf-8
date: Sun, 26 Dec 2021 09:45:17 GMT
x-amz-apigw-id: K83zFHKzIAMFmqA=
x-amzn-errortype: ForbiddenException
x-amzn-requestid: 0c0e5e80-98bb-41bd-b0d2-6fdf145f4e7d
X-Content-Type-Options: nosniff

It was working yesterday, and I have not changed any code. However, it seems like the CORS policy is suddenly blocking fetching of an API…

I have been looking for answers for 5 hours on this site and many more. However, many answers did not work, and most of them had to do with backend..

My app does not have a backend. I fetch everything in useEffect.

KORconnect is a proxy server I use to hide my api key.

Please suggest me a possible solution..

This is the frontend code where I call fetch. It was working yesterday without commented out code.

 const Container = (): ReactElement => {
    const dispatch = useDispatch();
    
    useEffect(() => {
        const options: object = {
            method: 'GET',
            url: 'https://joonkim025n.korconnect.io/Rapid/cards',
            params: {collectible: '1'},
            // mode: 'no-cors',
            headers : { "x-api-key": "asdasdasdasdadsdayLOr0",
            // 'Access-Control-Allow-Origin':  "*",
            // 'Access-Control-Allow-Methods': 'GET',
            // 'Access-Control-Allow-Headers':  "Origin, X-Requested-With, Content-Type, Accept"
            }
        }
       
        // function to fetch all collectible cards from hearthstone api
        const fetchAllCards = async (): Promise<any> => {
            try {
                const response = await axios.request(options); 
                dispatch({type: 'SET_ALL_CARD', payload: response.data})
            } catch(e) {
                console.log(e)
            }
        }
        fetchAllCards();
    }, []);

    return ( // omitted...

Please take a look, thanks

Why my .find() is sending undefined after getting conditional result true in express js [duplicate]

const data = {
    employees: require("../data/employees.json"),
    setEmployees: function (data) { this.employees = data; }

};

const getAllEmployeesData = (requestt, responsee) => {
    responsee.json(data.employees)
}

const getSpecificEmployee = (req, res) => {
    const employee = data.employees.find((emp) => { emp.id === parseInt(req.params.id);});
    if (!employee) {
        return res.status(400).json({ "message": `Employee ID ${req.params.id} not found` });
    }
    const filteredArray = data.employees.filter(emp => emp.id === parseInt(req.body.id));
    data.setEmployees([...filteredArray])
    res.json(data.employees);
}

in this line const employee = data.employees.find((emp) => { emp.id === parseInt(req.params.id);}); in above code employee is showing undefined but the conditional statement is returning true
and also no such error like MODULE NOT FOUND that means nothing is wrong while importing my employee.json

my employees.json file

[
{
“id”: 1,
“firstname”: “hello”,
“lastname”: “bye”
},
{
“id”: 2,
“firstname”: “you”,
“lastname”: “me”
}
]

How to use SAP Crystal Reports in a Node.js application

I am trying to use SAP Crystal Reports in an Electron application (a desktop Node.js application). I have a few *.rpt files that should read data from an SQLite database and then print some reports.

But it looks like there is no JavaScript library that would enable me to do that. The only thing I have found is SAP Crystal Reports JavaScript API which is just a client library for SAP Business Intelligence Platform that I don’t use. I simply need to print some reports without relying on any external server.

Has anybody managed to make printing work with Crystal Reports in a Node.js application?

React – Handling multiple state in button

I have a simple function that handle state for multiple button and create a dynamic class. Here in my code i have successfully changed the state for onclick event. I want to change the class color dynamically for onclick event, but the class isn’t changing. What did i do wrong here? I’ve been struggling with simple things

import React, { useEffect, useState } from 'react'

function Tes() {
    const lst = [
        {
            'name' : 'Python',
            'active': true,
            'disabled': false
        },
        {
            'name' : 'Java',
            'active': false,
            'disabled': true
        },
        {
            'name' : 'PHP',
            'active': true,
            'disabled': false
        },
        {
            'name' : 'C++',
            'active': true,
            'disabled': false
        },
        {
            'name' : 'Javascript',
            'active': false,
            'disabled': true
        },
        {
            'name' : 'Django',
            'active': true,
            'disabled': false
        }
    ]

    const [statebtn, setStatebtn] = useState(lst)


    function onClick(key, index) {
        let tmp = statebtn;
        tmp[index][key] = !tmp[index][key];
        setStatebtn(tmp);
        console.log(statebtn, 'fsadsada');
    }

    function changeClass(statevalue) {
        return (statevalue ? "btn-primary" : "btn-danger")
    }




    return (
        <div>
            {lst.map((x,index) => (
                <button onClick={() => onClick('active', index)} className={`btn ${statebtn[index]['active'] ? "btn-primary" : "btn-danger"}`} disabled={x['disabled']}>{x['name']}</button>
            ))
            }

        </div>
    )
}

export default Tes

ESLint configuration in package.json is invalid In react-bootstrap for dashboard

I have a dashboard bootstrap in reactjs when i run the dashboard i receive this error

"ESLint configuration in package.json is invalid:
        - Unexpected top-level property "babelOptions"."

I don’t understand what ESLint is but I believe it is a set of rules for the way the code is written.

I don’t understand what this error means it is appearing in the package.json structure.

is there a way to disable Eslint or fix this issue?

here is my package.json file:

{
  "name": "skote-react-hook",
  "version": "2.0.0",
  "private": true,
  "dependencies": {
    "@ckeditor/ckeditor5-build-classic": "^31.0.0",
    "@ckeditor/ckeditor5-react": "^3.0.3",
    "@fullcalendar/bootstrap": "^5.10.1",
    "@fullcalendar/core": "^5.10.1",
    "@fullcalendar/daygrid": "^5.10.1",
    "@fullcalendar/interaction": "^5.10.1",
    "@fullcalendar/react": "^5.10.1",
    "@lourenci/react-kanban": "^2.1.0",
    "@testing-library/jest-dom": "^5.15.0",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "@vtaits/react-color-picker": "^0.1.1",
    "apexcharts": "3.30.0",
    "axios": "^0.21.1",
    "axios-mock-adapter": "^1.20.0",
    "bootstrap": "^5.1.3",
    "chart.js": "^2.9.4",
    "chartist": "^0.11.4",
    "classnames": "^2.3.1",
    "draft-js": "^0.11.7",
    "echarts": "^4.9.0",
    "echarts-for-react": "^3.0.1",
    "firebase": "^9.0.1",
    "formik": "^2.2.9",
    "google-maps-react": "^2.0.6",
    "i18next": "^20.3.1",
    "i18next-browser-languagedetector": "^6.1.1",
    "leaflet": "^1.7.1",
    "lodash": "^4.17.21",
    "lodash.clonedeep": "^4.5.0",
    "metismenujs": "^1.3.0",
    "moment": "2.29.1",
    "node-sass": "^6.0.1",
    "nouislider-react": "^3.4.0",
    "prop-types": "^15.7.2",
    "react": "^17.0.2",
    "react-apexcharts": "^1.3.9",
    "react-auth-code-input": "^1.2.1",
    "react-bootstrap-editable": "^0.8.2",
    "react-bootstrap-sweetalert": "^5.2.0",
    "react-bootstrap-table-next": "^4.0.3",
    "react-bootstrap-table2-editor": "^1.4.0",
    "react-bootstrap-table2-paginator": "^2.1.2",
    "react-bootstrap-table2-toolkit": "^2.1.3",
    "react-chartist": "^0.14.4",
    "react-chartjs-2": "^2.11.1",
    "react-color": "^2.19.3",
    "react-countdown": "^2.3.2",
    "react-datepicker": "^4.1.1",
    "react-dom": "^17.0.2",
    "react-draft-wysiwyg": "^1.14.7",
    "react-drag-listview": "^0.1.8",
    "react-dropzone": "^11.3.2",
    "react-dual-listbox": "^2.1.2",
    "react-facebook-login": "^4.1.1",
    "react-flatpickr": "^3.10.7",
    "react-google-login": "^5.2.2",
    "react-i18next": "^11.10.0",
    "react-image-lightbox": "^5.1.1",
    "react-input-mask": "^2.0.4",
    "react-jvectormap": "^0.0.16",
    "react-leaflet": "^2.7.0",
    "react-meta-tags": "^1.0.1",
    "react-modal-video": "^1.2.7",
    "react-native-inline-datepicker": "^1.2.0",
    "react-perfect-scrollbar": "^1.5.8",
    "react-rangeslider": "^2.2.0",
    "react-rating": "^2.0.5",
    "react-rating-tooltip": "^1.2.0",
    "react-redux": "^7.2.4",
    "react-responsive-carousel": "^3.2.18",
    "react-router-dom": "^5.2.0",
    "react-script": "^2.0.5",
    "react-scripts": "^4.0.3",
    "react-select": "^4.3.1",
    "react-sparklines": "^1.7.0",
    "react-star-ratings": "^2.3.0",
    "react-super-responsive-table": "^5.2.0",
    "react-switch": "^6.0.0",
    "react-table": "^7.7.0",
    "react-time-picker": "^4.3.0",
    "react-toast-notifications": "^2.4.4",
    "reactstrap": "^9.0.1",
    "recharts": "^2.1.5",
    "redux": "^4.1.1",
    "redux-form": "^8.3.7",
    "redux-saga": "^1.1.3",
    "simplebar-react": "^2.3.6",
    "toastr": "^2.1.4",
    "yup": "^0.32.11"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts --max_old_space_size=8000 build",
    "lint": "eslint .",
    "lint:fix": "eslint --fix .",
    "format": "prettier --write "**/*.{js,jsx,json,md,html,css,less,scss}"",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "eslint:recommended",
      "plugin:react/recommended"
    ],
    "babelOptions": {
      "presets": [
        "@babel/preset-react"
      ]
    },
    "parser": "@babel/eslint-parser",
    "parserOptions": {
      "requireConfigFile": false,
      "ecmaVersion": 2020,
      "sourceType": "module",
      "ecmaFeatures": {
        "jsx": true
      }
    },
    "env": {
      "browser": true,
      "es6": true
    },
    "globals": {
      "$": true
    },
    "settings": {
      "react": {
        "version": "^17.0.1"
      }
    },
    "rules": {
      "semi": [
        "error",
        "never"
      ]
    }
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "resolutions": {
    "moment": "2.29.1"
  },
  "devDependencies": {
    "babel-eslint": "^10.1.0",
    "eslint": "^7.32.0",
    "eslint-config-standard-react": "^9.2.0",
    "eslint-plugin-react": "^7.20.6",
    "prettier": "^2.1.1"
  }
}

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 while fetching get route

I am trying to fetch a get route from a nodejs api that returns some json data. How ever when I try to make a request to that route, I get this message in my browser console :Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Here is the nodejs api code:

app.get('/vusers',(req,res)=>{
console.log("got a request")
return res.json({"message":"hello"})
 })

Here is the reactjs code that makes the request:

 useEffect(()=>{
    fetch('/vusers',{
        headers:{
            'Accept': 'application/json'
        }
    })
    .then(res=>res.json())
    .then(result=>{
        console.log(result)
    })
},[])