简体   繁体   中英

How to import a variable from another file

How can I import a variable of my file called routen.js to my file called main.js. I tried it with this command: import {a} from '../../routen/routen.js' But then I got an Error "SyntaxError: Unexpected token '{'. import call expects exactly one argument."

How can I fix it?

I don't use an export but the variable is set here:

    let a = false;
    exports.login = function(request, response){
    var login = request.body.loginname;
    var pwd = request.body.loginpassword;

    let sql = 'SELECT * FROM Benutzer WHERE Benutzername =? AND Passwort =?';
    db.get(sql, login, pwd, (err, row)=>{
   if(row) {
   console.log("Anmeldung erfolgreich.");
   a = true;
   
    }

  else{
    console.log("Anmeldung fehlgeschlagen.");
    a = false;
}

  });
  response.redirect("/");
  response.end();
 };

In general:

File: routen.js

let a = false;
exports.a = a;

File: main.js

var a = require("./routen");
console.log(a);

node main.js shows

$ node main.js 
{ a: false }

for your case:

// file: ./routen.js
exports.login = function (request, response) {
  var login = request.body.loginname;
  var pwd = request.body.loginpassword;

  let sql = "SELECT * FROM Benutzer WHERE Benutzername =? AND Passwort =?";
  db.get(sql, login, pwd, (_err, row) => {
    if (row) {
      console.log("Anmeldung erfolgreich.");
      return true;
    } else {
      console.log("Anmeldung fehlgeschlagen.");
      return false;
    }
  });
  response.redirect("/");
  response.end();
};

// file: main.js
var a = require("./routen");
console.log(a.login(req, res)); // should then print false/true

I would change exports.login to at the end of that file module.exports = login in the case login is the function name you are exporting.

to import use the old var login = require('./routen');

I am not sure if in version 10 you can destructure on import so better go to the secure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM