mysql TypeError:赋值给常量变量

unhi4e5o  于 2023-08-02  发布在  Mysql
关注(0)|答案(4)|浏览(127)

请帮我解决这个错误。我附上了我的index.js代码routes.js代码和db.js代码以及错误描述。我一直在努力解决这个错误。
index.js

const express = require('express');
const app = express();
const routes = require('./routes');
const path = require('path');

const fileUpload = require('express-fileupload');
const bodyParser = require('body-parser');

const session = require('express-session');
const auth = require('./routes/auth');
const {
  con,
  sessionStore
} = require('./config/db');
const fs = require('fs');

require('dotenv').config({
  path: path.join(__dirname, '.env')
});
const port = process.env.PORT || 3000;

// parse application/json
app.use(bodyParser.json())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
  extended: false
}));

//static files 
app.use(express.static('public'))
app.use('/css' , express.static(__dirname + 'public/css'))
app.use('/imgs' , express.static(__dirname + 'public/imgs'))

var sess = {
    secret: 'keyboard cat',
    store: sessionStore,
    cookie: {
      httpOnly: false,
    },
    resave: false,
    saveUninitialized: false
  }
  
  app.use(session(sess));
  app.use(fileUpload());
//set views
app.set('view engine' , 'ejs');
app.set('views', path.join(__dirname, 'views'))

//
app.use(require('connect-flash')());
app.use((req, res, next) => {
  res.locals.messages = require('express-messages')(req, res);
  next();
});
app.get('/', (req,res) =>{
    res.render('index22')
})
app.get('/login', (req, res) => {
    res.render('login');
   });

   let s;

const loginRequired = (req, res, next) => {
    if (req.session.username) {
    s = req.session;
    next();
    } else {
    res.redirect('/auth/login');
    }
}
// app.get('/new', (req, res) => {
//   res.render('new');
//  });

//  app.get('/show', (req, res) => {
//   res.render('show');
//  });

// app.get('/', loginRequired, (req, res) => {
//     res.redirect('/new');
// });
// app.get('/', loginRequired, (req, res) => {
//   res.redirect('/show');
// });

 
app.get('/new', loginRequired, routes.new);//call for main index page
app.post('/new', loginRequired, routes.new);//call for signup post 
app.get('/show', loginRequired, routes.show);





app.use('/auth', auth);

app.listen(port, () => console.log(`listening on http://${process.env.HOST}:${port}`));

字符串
routes.js

const {
   con,
   sessionStore
 } = require('./config/db');
exports.new = function(req, res){
    message = '';
   if(req.method == "POST"){
      const post  = req.body;
      const username= post.username;
      const title= post.title;
      const state= post.state;
      const category= post.category;
      const description= post.description;
 
      if (!req.files)
                return res.status(400).send('No files were uploaded.');
 
        const file = req.files.uploads;
        const img_name=file.name;
 
         if(file.mimetype == "image/jpeg" ||file.mimetype == "image/png"||file.mimetype == "image/gif" ){
                                 
              file.mv('public/imgs/uploads/'+file.name, function(err) {
                             
                  if (err)
 
                    return res.status(500).send(err);
                        const sql = "INSERT INTO `nt_data`(`username`,`title`,`state`,`category`, `img_name` ,`description`) VALUES ('" + username + "','" + title + "','" + state + "','" + category + "','" + image + "','" + description + "')";
 
                            const query = con.query(sql, function(err, result) {
                                 res.redirect('show/'+result.insertUsername);
                            });
                       });
          } else {
            message = "This format is not allowed , please upload file with '.png','.gif','.jpg'";
            res.render('new.ejs',{message: message});
          }
   } else {
      res.render('new');
   }
 
};

exports.show = function(req, res){
    const message = '';
    const username = req.params.username;
    const sql="SELECT * FROM `nt_data` WHERE `username`='"+username+"'"; 
    con.query(sql, function(err, result){
      if(result.length <= 0)
      message = "show not found!";
      
      res.render('show.ejs',{data:result, message: message});
   });
};


db.js

const mysql = require('mysql');
const path = require('path');
const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);
require('dotenv').config({ path: path.join(__dirname, '../.env') });

// config for your database
const con = mysql.createConnection({
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    server: process.env.DB_HOST,
    database: process.env.DB_NAME,
    port: parseInt(process.env.DB_PORT)
});

var sessionStore = new MySQLStore({}/* session store options */, con);

// connect to your database
con.connect((err) => {
    if (err) throw err;
    console.log("Connected to database");
});

module.exports = { con, sessionStore };


错误描述:

C:\Users\hp\Desktop\Internship\Nt\node_modules\mysql\lib\protocol\Parser.js:437
      throw err; // Rethrow non-MySQL errors
      ^

TypeError: Assignment to constant variable.
    at Query.<anonymous> (C:\Users\hp\Desktop\Nt\routes.js:50:12)
    at Query.<anonymous> (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\Connection.js:526:10)
    at Query._callback (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\Connection.js:488:16)
    at Query.Sequence.end (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
    at Query._handleFinalResultPacket (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\sequences\Query.js:149:8)
    at Query.EofPacket (C:\Users\hp\Desktop\\Nt\node_modules\mysql\lib\protocol\sequences\Query.js:133:8)
    at Protocol._parsePacket (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\Protocol.js:291:23)
    at Parser._parsePacket (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\Parser.js:433:10)
    at Parser.write (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\Parser.js:43:10)
    at Protocol.write (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\Protocol.js:38:16)


我猜主要错误是在routes.js文件任何帮助将非常感谢。谢谢你的好意

xj3cbfub

xj3cbfub1#

只需在show函数中将const更新为let

exports.show = function(req, res){
    let message = '';
    const username = req.params.username;
    const sql="SELECT * FROM `nt_data` WHERE `username`='"+username+"'"; 
    con.query(sql, function(err, result){
      if(result.length <= 0)
      message = "show not found!";
      
      res.render('show.ejs',{data:result, message: message});
   });
};

字符串
或者,如果你真的不需要重新分配它,只需在主体中创建变量if if语句:

exports.show = function(req, res){
    const username = req.params.username;
    const sql="SELECT * FROM `nt_data` WHERE `username`='"+username+"'"; 
    con.query(sql, function(err, result){
      if(result.length <= 0)
      const message = "show not found!";
      
      res.render('show.ejs',{data:result, message: message});
   });
};


希望这有帮助!

bihw5rsg

bihw5rsg2#

一旦声明了const,就不能重新分配它。查看MDN docs以了解更多信息。
这样不行

const message = ""
message = "show not found!";

字符串
这将

let message = ""
message = "show not found!"

qni6mghb

qni6mghb3#

我在connect-mongo上遇到了类似的问题。仔细检查express-mysql-session的最新文档,并检查您是否意外地导入了您已经需要的包。有时,像Visual Studio Code这样的IDE会这样做。它通过IDE导入const{express-session}并将其分配给mongostore。

63lcw9qa

63lcw9qa4#

当试图修改或重新声明使用const关键字声明的变量时,会发生“赋值给常量变量”错误。在JavaScript中,使用const声明的变量是只读的,并且在初始化后不能重新分配新值。此行为可确保变量在其整个范围内保持恒定。若要修复此错误,请考虑在需要更新变量值时使用let关键字而不是const。或者,请确保您没有无意中尝试重新分配常量变量。请记住,const适用于在执行过程中保持不变的值,而let更适合于可变变量。
作为一个例子,我给出了一个代码。

const pi = 3.14; // This variable cannot be reassigned a new value

// To fix the error, use 'let' if you need to change the value
let counter = 0;
counter = 1; 
// This is valid with 'let', but not with 'const'

字符串
使用let而不是const允许您在需要时修改变量的值,避免“赋值给常量变量”错误。
所以我试着找出错误在哪里!
在router.js文件中更新const以let或var可以解决这个问题。这里是更新的代码。

exports.show = function(req, res){
    let message = '';
    const username = req.params.username;
    const sql="SELECT * FROM `nt_data` WHERE `username`='"+username+"'"; 
    con.query(sql, function(err, result){
      if(result.length <= 0)
      message = "show not found!";
      
      res.render('show.ejs',{data:result, message: message});
   });
};

相关问题