简体   繁体   中英

How do I import getToken function from util.js file without getting an error?

I'm writing my first React.js app and I had a problem while trying to use getToken function which I defined in the util.js file. I keep getting error 500. How should I import/fix the function?

userRoute

const router=express.Router() ;
router.post('/signin' , async (req,res)=>{
    const signinUser=await User.findOne({
        email:req.body.email ,
        password: req.body.password 
    });
    if(signinUser){
        res.send({
            _id:signinUser.id ,
            name:signinUser.name ,
            email:signinUser.email,
            isAdmin: signinUser.isAdmin ,
            token: getToken(signinUser)
            
        } );

    }
    else {
        res.status(401).send({msg:'invalid email or password'})
    }
})

util.js

import jwt from 'jsonwebtoken';
import config from './config'

const getToken =  (user)=>{
    return jwt.sign({
        _id:user.id ,
        password:user.password ,
        email:user.email ,
        isAdmin:user.isAdmin 
    } ,config.JWT_SECRET , {
        expiresIn : '72h'
    })
}

export {
    getToken
}

config.js

export  default{
    MONGODB_URL: process.env.MONGODB_URL || 'mongodb://localhost:/AdA' ,
    JWT_SECRET: process.env.JWT_SECRET || 'velyvelysecret'

}

you can do a named export or a default export

named export

export const getToken = () => {}
//usage
import {getToken} from './yourfilehere'

default export

export defefault getToken
//usage
export getToken from './yourfilehere'

you can see more details with the mdn docs

https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Sentencias/export

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