在节点 js“应该设置秘密”和反应“npm ERR!代码 ELIFECYCLE”中出现错误
Posted
技术标签:
【中文标题】在节点 js“应该设置秘密”和反应“npm ERR!代码 ELIFECYCLE”中出现错误【英文标题】:Getting error in node js "secret should be set" and in react "npm ERR! code ELIFECYCLE" 【发布时间】:2020-09-08 13:48:42 【问题描述】:我正在 Mern Stack 做一个项目。我对后端开发相当陌生,mern stack 是我第一次遇到。一切都很顺利,我尝试使用条纹 js,它运行良好,但我不想在我的项目中使用它。所以我决定用我之前的代码替换我的整个文件夹。 现在的问题是我错误地删除了前端和后端部分的 .env 文件以及 package.json 文件。 我尝试通过再次创建 .env 文件来解决此问题,并在删除所有节点模块文件后执行 npm install ,但似乎没有任何效果。它在后端的 node_modules 部分给出错误“错误:应设置秘密” 以及前端的这个错误
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! projfrontend@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the projfrontend@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Raj98\AppData\Roaming\npm-cache\_logs\2020-05-21T19_16_38_946Z-debug.log
D:\projfrontend>npm update
> core-js-pure@3.6.5 postinstall D:\projfrontend\node_modules\core-js-pure
> node -e "tryrequire('./postinstall')catch(e)"
//node_modules>express_jwt
var jwt = require('jsonwebtoken');
var UnauthorizedError = require('./errors/UnauthorizedError');
var unless = require('express-unless');
var async = require('async');
var set = require('lodash.set');
var DEFAULT_REVOKED_FUNCTION = function(_, __, cb) return cb(null, false); ;
function isFunction(object)
return Object.prototype.toString.call(object) === '[object Function]';
function wrapStaticSecretInCallback(secret)
return function(_, __, cb)
return cb(null, secret);
;
module.exports = function(options)
if (!options || !options.secret) throw new Error('secret should be set');
var secretCallback = options.secret;
if (!isFunction(secretCallback))
secretCallback = wrapStaticSecretInCallback(secretCallback);
var isRevokedCallback = options.isRevoked || DEFAULT_REVOKED_FUNCTION;
var _requestProperty = options.userProperty || options.requestProperty || 'user';
var _resultProperty = options.resultProperty;
var credentialsRequired = typeof options.credentialsRequired === 'undefined' ? true : options.credentialsRequired;
var middleware = function(req, res, next)
var token;
if (req.method === 'OPTIONS' && req.headers.hasOwnProperty('access-control-request-headers'))
var hasAuthInAccessControl = !!~req.headers['access-control-request-headers']
.split(',').map(function (header)
return header.trim();
).indexOf('authorization');
if (hasAuthInAccessControl)
return next();
if (options.getToken && typeof options.getToken === 'function')
try
token = options.getToken(req);
catch (e)
return next(e);
else if (req.headers && req.headers.authorization)
var parts = req.headers.authorization.split(' ');
if (parts.length == 2)
var scheme = parts[0];
var credentials = parts[1];
if (/^Bearer$/i.test(scheme))
token = credentials;
else
if (credentialsRequired)
return next(new UnauthorizedError('credentials_bad_scheme', message: 'Format is Authorization: Bearer [token]' ));
else
return next();
else
return next(new UnauthorizedError('credentials_bad_format', message: 'Format is Authorization: Bearer [token]' ));
if (!token)
if (credentialsRequired)
return next(new UnauthorizedError('credentials_required', message: 'No authorization token was found' ));
else
return next();
var dtoken;
try
dtoken = jwt.decode(token, complete: true ) || ;
catch (err)
return next(new UnauthorizedError('invalid_token', err));
async.waterfall([
function getSecret(callback)
var arity = secretCallback.length;
if (arity == 4)
secretCallback(req, dtoken.header, dtoken.payload, callback);
else // arity == 3
secretCallback(req, dtoken.payload, callback);
,
function verifyToken(secret, callback)
jwt.verify(token, secret, options, function(err, decoded)
if (err)
callback(new UnauthorizedError('invalid_token', err));
else
callback(null, decoded);
);
,
function checkRevoked(decoded, callback)
isRevokedCallback(req, dtoken.payload, function (err, revoked)
if (err)
callback(err);
else if (revoked)
callback(new UnauthorizedError('revoked_token', message: 'The token has been revoked.'));
else
callback(null, decoded);
);
], function (err, result)
if (err) return next(err);
if (_resultProperty)
set(res, _resultProperty, result);
else
set(req, _requestProperty, result);
next();
);
;
middleware.unless = unless;
middleware.UnauthorizedError = UnauthorizedError;
return middleware;
;
module.exports.UnauthorizedError = UnauthorizedError;
//auth.js(控制器)
const User = require("../models/user");
const check, validationResult = require("express-validator");
var jwt = require("jsonwebtoken");
var expressJwt = require("express-jwt");
exports.signup = (req, res) =>
const errors = validationResult(req);
if (!errors.isEmpty())
return res.status(422).json(
error: errors.array()[0].msg
);
const user = new User(req.body);
user.save((err, user) =>
if (err)
return res.status(400).json(
err: "NOT able to save user in DB"
);
res.json(
name: user.name,
email: user.email,
id: user._id
);
);
;
exports.signin = (req, res) =>
const errors = validationResult(req);
const email, password = req.body;
if (!errors.isEmpty())
return res.status(422).json(
error: errors.array()[0].msg
);
User.findOne( email , (err, user) =>
if (err || !user)
return res.status(400).json(
error: "USER email does not exists"
);
if (!user.autheticate(password))
return res.status(401).json(
error: "Email and password do not match"
);
//create token
const token = jwt.sign( _id: user._id , process.env.SECRET);
//put token in cookie
res.cookie("token", token, expire: new Date() + 9999 );
//send response to front end
const _id, name, email, role = user;
return res.json( token, user: _id, name, email, role );
);
;
exports.signout = (req, res) =>
res.clearCookie("token");
res.json(
message: "User signout successfully"
);
;
//protected routes
exports.isSignedIn = expressJwt(
secret: process.env.SECRET,
userProperty: "auth"
);
//custom middlewares
exports.isAuthenticated = (req, res, next) =>
let checker = req.profile && req.auth && req.profile._id == req.auth._id;
if (!checker)
return res.status(403).json(
error: "ACCESS DENIED"
);
next();
;
exports.isAdmin = (req, res, next) =>
if (req.profile.role === 0)
return res.status(403).json(
error: "You are not ADMIN, Access denied"
);
next();
;
//auth.js(路由)
var express = require("express");
var router = express.Router();
const check, validationResult = require("express-validator");
const signout, signup, signin, isSignedIn = require("../controllers/auth");
router.post(
"/signup",
[
check("name", "name should be at least 3 char").isLength( min: 3 ),
check("email", "email is required").isEmail(),
check("password", "password should be at least 3 char").isLength( min: 3 )
],
signup
);
router.post(
"/signin",
[
check("email", "email is required").isEmail(),
check("password", "password field is required").isLength( min: 1 )
],
signin
);
router.get("/signout", signout);
module.exports = router;
//app.js
require("dotenv").config();
const mongoose = require("mongoose");
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const cors = require("cors");
//My routes
const authRoutes = require("./routes/auth");
const userRoutes = require("./routes/user");
const categoryRoutes = require("./routes/category");
const productRoutes = require("./routes/product");
const orderRoutes = require("./routes/order");
//DB Connection
mongoose
.connect(process.env.DATABASE,
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
)
.then(() =>
console.log("DB CONNECTED");
);
//Middlewares
app.use(bodyParser.json());
app.use(cookieParser());
app.use(cors());
//My Routes
app.use("/api", authRoutes);
app.use("/api", userRoutes);
app.use("/api", categoryRoutes);
app.use("/api", productRoutes);
app.use("/api", orderRoutes);
//PORT
const port = process.env.PORT || 8000;
//Starting a server
app.listen(port, () =>
console.log(`app is running at $port`);
);
我正在结束这个项目,不幸的是把所有事情都搞砸了。请帮助我摆脱困境
后端错误SS:https://i.stack.imgur.com/AJHxe.png
前端错误的SS:https://i.stack.imgur.com/PqkvI.png
【问题讨论】:
在你自己的源文件中搜索process.env.
(不包括node_modules)——这会告诉你需要在.env
中设置什么值。该错误是由 jwt.sign
使用 process.env.SECRET
引起的,目前可能未定义。
在 .env 文件中,我连接了我的数据库并将其保存在 app.js 中作为 process.env.DATABASE 但不起作用
【参考方案1】:
尝试首先对 process.env.SECRET 进行硬核(其中值应与 env 文件匹配),如果可行,请尝试:
require('dotenv').config( path: 'env file path' )
在文件中。
另外,请尝试将 require('dotenv').config( path: 'env file path' )
放在 require 语句的顶部或顶部范围内的某个位置。
【讨论】:
【参考方案2】:我的问题是 require('dotenv')
和 const authRoutes = require('./routes/auth');
与 server.js
的顺序不正确。
在我的原始代码中,我有
const authRoutes = require("./routes/auth");
require("dotenv").config();
所以在挖了网之后,我从https://github.com/linnovate/meanio/issues/53找到了解决方案。 require("dotenv").config();
应该是第一个,然后是 const authRoutes = require("./routes/auth");
,如下所示。
require("dotenv").config();
const authRoutes = require("./routes/auth");
【讨论】:
干得好,我只是在这里和那里寻找相同的答案。最终我在这里找到了它。非常感谢。【参考方案3】:在我的情况下,我更新了 expressJwt,其中强制添加密钥和算法。
喜欢这个
const authenticate = jwt(
secret: 'secret',
algorithms: ['HS256']
);
【讨论】:
以上是关于在节点 js“应该设置秘密”和反应“npm ERR!代码 ELIFECYCLE”中出现错误的主要内容,如果未能解决你的问题,请参考以下文章
如何解决 npm 错误“npm ERR!代码 ELIFECYCLE”
在 npm install 上出现错误,因为 npm ERR cb() 从未调用过