0

I want to write a comment system in nodejs and I don't understand why the person variable is declared in app.use(multer({dest:"public/uploads/"+${uploadFile}}).single("filedata")); defined as undefined.

I save data from mysql to an object on nodejs(express) if you access: app.get("/cabin",auth, (request, response) => { response.render('cabin',{ login:${person.login} } There is a login, but as soon as I try to go beyond "app.get or app.post" then the whole object remains undefined. I tried to look for the scope, used global.login. But the problem remains. Object var person={}; declared empty before accessing sql then opens SQL after for there is a selection with login and name, password. It is necessary to save this part to the buffer for id, not just an object with sql, in general, everything that was written disappears, so I open sql within app.use(passport... (authUser)-gets a login password to enter the site, ok! But then all the data can only be used in the scope of app.get and if you try to create a folder app.use(multer({dest:"public/uploads/"+${uploadFile}}).single("filedata")); then the directory is called undefined How do I make an object visible throughout the script? Looking for some kind of buffer for data in nodejs Maybe there is some way? Authorization goes through FOR on all MySQL and after authorization, it would be desirable to save the card so that the data remains in the global scope. global.login - also returns undefined. Or what to do then? enter image description here In the image, the directory is created with the normal name everything is ok, but outside the function auntUser object the person no longer exists.

app.use(passport.initialize());
app.use(passport.session());
 authUser = async (user, password, done) => {
    console.log(`User is ${user}`);
    console.log(`Password is ${password}`);
    function usPas(){
    console.log("^_^"+`${user}`);
    console.log("***"+`${password}`);
    }
    await usPas();
    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    const pathUser='user';


    const connection = mysql.createConnection({
      host: `${mysqlhost}`,
      user: `${mysqluser}`,
      password: `${mysqlpassword}`,
      database: `${mysqldatabase}`
    });
      connection.connect(err=>{
        if(err){
          return err;
          console.log('err');
        }else{
          console.log('database--- oK');
        }
      });
      const sql = `SELECT * FROM barbarians`;
      connection.query(sql, function(err, results) {
        if(err) console.log(err);
        // console.log(results.length);
        // console.log(results);

  for(let y=0;y<results.length;y++){
    // console.log(results[y].login+"____"+results[y].password+"___"+'////'+`${user}`+"---"+`${password}`+'_FIRST-PUSH');
    if(results[y].login==`${user}`&&results[y].password==`${password}`){

      
    person={
        id:results[y].id,
        login:results[y].login,
        pwd:results[y].password,
        email:results[y].email,
        name:results[y].Name,
        lastname:results[y].Lastname,
        age:results[y].age,
        gender:results[y].gender,
        blod_type:results[y].blod_type,
        profession:results[y].profession,
        having_children:results[y].having_children,
        marital_status:results[y].marital_status,
        hobby:results[y].hobby,
        education:results[y].education,
        visit_date:results[y].visit_date,

      }
      fs.writeFile('public/uploads/globalName.json',`${person.login}`,(err)=>{
        if(err) console.log(err);
        else console.log('oK');
      });
      // global.login=`${person.login}`;
      function personLoginAndProfile(){
        // const globalName=fs.writeFileSync('public/uploads/globalName.json',`${person.login}`);
        global.login=`${person.login}`;
        const folderName='public/uploads/'+`${person.login}`;
        try{
          if(!fs.existsSync(folderName)){
            fs.mkdirSync(folderName);
          }
        }catch(err){
          console.log(err);
        }
      }
      personLoginAndProfile();//<-this function throws an error file is created but the page redirects to an error: The connection was reset
      // console.log(person.login+'___<- if login');

    }else{
      // console.log('FALSE');
    }
    // var logins=results[y].login;
    // var password=results[y].password;

  }

        });//connection
        // console.log(`${logina}`+"<---------------------------");

      //******************************************************************************


      //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

        connection.end(err=>{
          if(err){
            return err;
            console.log('err');
          }else{
            console.log('database ADD --- closed');
          }
        });//connection closed

      //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXxxxxx
      setTimeout(()=>{


        // console.log(`${person.login}`+"////"+ `${person.pwd}`+'<---------What?');
        // console.log(`${user}`+"////"+ `${password}`+'<---------What two?')
        //a miracle happens here
        // function vsePush(){
          if (user == `${person.login}` && password == `${person.pwd}`) {
            return done(null, { id: `${person.id}`, name: `${person.login}` ,visit_date:`${person.visit_date}`});
          }else{
            // message='incorrect login or password';
          }
          return done(null, false);

      },700);
      // }

}//authUser
console.log(typeof(authUser));
passport.use(new LocalStrategy(authUser));
passport.serializeUser((user, done) => {
    done(null, user)
});
passport.deserializeUser((user, done) => {
    done(null, user)
});

app.post("/login", passport.authenticate('local', {
    successRedirect: "/home",
    failureRedirect: "/login",
}));


app.get("/login", (request, response) => {
  
  
    response.render('login',{
      title:"authorization",
      text: "TEXT",
      description: "ddfs",
      info: `${message}`
    });
});

auth = (request, response, next) => {
    if (request.user != undefined) next();
    response.redirect("/login");// ОШИБКА
    // message='not login or password';
}

app.post("/exit", (request, response) => {
  request.logOut();
  response.redirect('/');
});
app.get("/home",auth, (request, response) => {

  response.render('home',{

    title:"authorization Success!",
    text: "777 laborum.",
    description: "ddfs",
    name: `${person.name}`

  });
});
app.get("/script",auth, (request, response) => {
  console.log('lol');
  response.render('script',{

    title:"authorization Success!",
    text: "Excess!",
    description: "ddfs",
    name: `${person.name}`

  });
});


app.get("/cabin",auth, (request, response) => {
  response.render('cabin',{
    title:"is this are cabins!",
    text: "This is actually real. Spacecraft control room!",
    description: "cabin user",
    name: `${person.name}`,
    login:`${person.login}`,
    email:`${person.email}`,
    name:`${person.name}`,
    lastname:`${person.lastname}`,
    gender:`${person.gender}`,
    age:`${person.age}`,
    blod_type:`${person.blod_type}`,
    profession:`${person.profession}`,
    having_children:`${person.having_children}`,
    marital_status:`${person.marital_status}`,
    hobby:`${person.hobby}`,
    education:`${person.education}`,
  });
  // console.log(ruquerst.url);
});
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
global.uploadFile=`${person.login}`;//why is the variable undefined???

function sendRes(url, contentType, res){
  let file=path.join(__dirname+'/public/upload/321/')
  fs.readFile(file,(err,content)=>{
    if(err){
      console.log(err);
    }else{
      res.writeHead(200,{'Content-Type': contentType});
      res.write('file not found');
      res.end();
    }
  })
};
// console.log(`${person.name}`+'<---------------------------------***')
// function getRandomInt(max) {
  //
  //   console.log(person.login+'0000000000000000000000000000000000000000000000');
  //   return Math.floor(Math.random() * max);
  // }
  // // global.login=getRandomInt(999);
  // // global.login=`${person.getFullName}`;
  // console.log(`${global.login}`+"<---------------------------");
  // console.log(`${global.login}`+"---<- Two LOGIN");
  app.use(express.static(__dirname+'/public'));

  // var uploadFile=`${person.name}`;
  global.uploadFile=`${person.login}`;
  app.use(multer({dest:"public/uploads/"+`${uploadFile}`}).single("filedata"));
  //in this place the code does not work the file name is undefined

  app.post("/public/upload", function (req, res, next) {

    console.log(req.url);
    let filedata = req.file;
    console.log(filedata);
    if(!filedata)
    res.send("err");
    else
    res.send("file uploaded");
  });
  //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
app.post('/cabinUpdateEmail',auth,(request,response)=>{
  response.render('cabin',{
    title:"is this are cabins!",
    text: "This is actually real. Spacecraft control room!",
    description: "cabin user",

    email:`${person.email}`,

  });
  const connection = mysql.createConnection({
    host: `${mysqlhost}`,
    user: `${mysqluser}`,
    password: `${mysqlpassword}`,
    database: `${mysqldatabase}`
  });
  connection.connect(err=>{
    if(err){
      return err;
      console.log('err');
    }else{
      console.log('database--- oK');
    }
  });

  const sql = `UPDATE barbarians SET email=? WHERE barbarians.id=${person.id}`;
const data = [`${request.body.email}`];
connection.query(sql,data, function(err, results) {
    if(err) console.log(err);
    console.log(results);
});
Amir
  • 1
  • 2

0 Answers0