Error: Cannot find module '../utils/appleAuth' on npm start - node.js

here is the imports that I am using currently to implement apple auth on the backend
const Joi = require('joi')
const logger = require('../common/logger')
const errors = require('../common/errors')
const helper = require('../common/helper')
const models = require('../models')
const _ = require('lodash')
const jwt = require('jsonwebtoken')
const ms = require('ms')
const constants = require('../../app-constants')
const userService = require('./UserService')
const adminCommonService = require('./admin/AdminCommonService')
const User = models.User
const VerificationCode = models.VerificationCode
const fs = require('fs');
const AppleAuth = require('apple-auth');
const config = fs.readFileSync("./config/config");
const auth = new AppleAuth(config, 'config/apple/authkey.p8')
/**apple auth
*/
const config = {
client_id: 'YOUR APP ID',
team_id: 'ZUU8485r88T',
redirect_uri: '', // Leave it blank
key_id: 'YOUR KEY ID',
scope: 'name%20email',
};
const appleAuth = new AppleAuth(
config,
fs.readFileSync('assets/apple/AuthKey_HVC8C93672.p8').toString(),
'text'
);
export const appleAuth = async (req: Request, res: Response){
const { token: appleToken } = req.body;
try {
//retrieve apple Data from AccessToken
const apple = await AppleAuth.accessToken(appleToken)
const appleData = jwt.decode(apple.id_token);
//get apple Id
const{sub:appleID}=appleData;
//count the number of connections of user
const user = await User.findOneAndUpdate(
{appleId},
{ $inc: { nbOfConnections: 1 } },
{upsert: true, new:true,userFindAndModify: false}
);
return res.status(200).json({user});
} catch (err) {
return res.status(500).json({message:err.message || err});
}
};
and here is what my package.json looks like:
main": "app.js",
"scripts": {
"start": "node app.js",
"lint": "standard",
"lint:fix": "standard --fix",
"clear-db": "node src/clear-db.js",
"test-data": "node src/test-data.js"
},
"author": "TCSCODER",
"license": "none",
"devDependencies": {
"standard": "^12.0.1"
},
"dependencies": {
"adm-zip": "^0.4.14",
"apple-auth": "^1.0.6",
"aws-sdk": "^2.636.0",
"axios": "^0.19.2",
"bcryptjs": "^2.4.3",
"bluebird": "^3.7.2",
"body-parser": "^1.15.1",
"bootstrap": "^4.5.2",
"config": "^3.0.0",
"core-util-is": "^1.0.2",
"cors": "^2.7.1",
"credit-card-type": "^8.3.0",
"express": "^4.14.0",
"get-parameter-names": "^0.3.0",
"googleapis": "^59.0.0",
"http-status-codes": "^1.4.0",
"joi": "^14.3.1",
"json-diff": "^0.5.4",
"json2csv": "^5.0.1",
"jsonwebtoken": "^8.5.1",
"lodash": "^4.17.15",
"mime-types": "^2.1.27",
"moment": "^2.24.0",
"moment-range": "^4.0.2",
"moment-timezone": "^0.5.27",
"mongodb": "^3.6.2",
"mongoose": "^5.8.9",
"mongoose-field-encryption": "^3.0.4",
"morgan": "^1.7.0",
"ms": "^2.1.2",
"multer": "^1.4.2",
"node-schedule": "^1.3.2",
"nodemailer": "^4.7.0",
"nylas": "^4.8.0",
"parse-duration": "^0.4.4",
"stripe": "^8.32.0",
"superagent": "^5.2.1",
"validator": "^10.9.0",
"winston": "^3.1.0"
},
"engines": {
"node": "12.x"
}
}
When i run npm start I get this error,
Any ideas?
internal/modules/cjs/loader.js:969
throw err;
^
Error: Cannot find module '../utils/appleAuth'
Require stack:
I have tried re installing npm, deleting my package.json folder and node modules folder. I have tried re installing the library as well with no luck. Every time I use npm start I get the same error. I am pretty new to api's and would love some help. thank you!

Related

TypeError: app.address is not a function - Shopify App Node.js

The issue is already describe here
Mocha API Testing: getting 'TypeError: app.address is not a function'
Tried to test my Shopify app using Mocha, Chai created with Nextjs. Tried several workarounds mentioned on the above link. But it still produces the following error
GET requests
GET /customers
1) Success should return true
0 passing (1s)
1 failing
1) GET requests
GET /customers
Success should return true:
TypeError: app.address is not a function
at serverAddress (node_modules\chai-http\lib\request.js:282:18)
at new Test (node_modules\chai-http\lib\request.js:271:53)
at Object.obj.<computed> [as get] (node_modules\chai-http\lib\request.js:239:14)
at Context.<anonymous> (test\appTest.js:44:10)
at processImmediate (node:internal/timers:466:21)
apptest.js
let chai = require("chai");
let chaiHttp = require("chai-http");
const server = require("../server/index");
chai.should();
chai.use(chaiHttp);
describe("GET requests", () => {
describe("GET /customers", () => {
it("Success should return true", (done) => {
chai.request(server)
.get("/customers")
.end((err, res) => {
console.log('Error => ', err);
console.log('Response => ', res);
res.body.success.should.equal(true)
done();
});
});
});
});
server.js
import "#babel/polyfill";
import createShopifyAuth, { verifyRequest } from "#shopify/koa-shopify-auth";
import Shopify, { ApiVersion } from "#shopify/shopify-api";
import dotenv from "dotenv";
import "isomorphic-fetch";
import Koa from "koa";
import Router from "koa-router";
import next from "next";
const mongoose = require("mongoose");
dotenv.config();
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({
dev,
});
const handle = app.getRequestHandler();
const AccessToken = {};
Shopify.Context.initialize({
API_KEY: process.env.SHOPIFY_API_KEY,
API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
SCOPES: process.env.SCOPES.split(","),
HOST_NAME: process.env.HOST.replace(/https:\/\/|\/$/g, ""),
API_VERSION: ApiVersion.January22,
//API_VERSION: ApiVersion.October20,
IS_EMBEDDED_APP: true,
// This should be replaced with your preferred storage strategy
SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
});
const ACTIVE_SHOPIFY_SHOPS = {};
app.prepare().then(async () => {
const server = new Koa();
const router = new Router();
server.keys = [Shopify.Context.API_SECRET_KEY];
server.use(
createShopifyAuth({
async afterAuth(ctx) {
// Access token and shop available in ctx.state.shopify
const { shop, accessToken, scope } = ctx.state.shopify;
AccessToken["access_token"] = accessToken;
ctx.cookies.set("accessToken", accessToken, {
httpOnly: false,
secure: true,
sameSite: "none",
});
ctx.cookies.set("shop_name", shop, {
secure: true,
sameSite: "none",
httpOnly: false,
});
const host = ctx.query.host;
ACTIVE_SHOPIFY_SHOPS[shop] = scope;
ctx.cookies.set("HOST", host, {
secure: true,
sameSite: "none",
httpOnly: false,
});
//Database Connection
const shopName = shop.replace("myshopify.com", "");
const formattedShopName = shopName
.replace(/[^a-z\d\s]+/gi, "")
.replace(/\s+/g, "")
.toLowerCase();
const connectionStr = `${process.env.CONNECTION_STRING}${formattedShopName}`;
await mongoose
.connect(connectionStr, {
// creds
})
.then(async () => {
console.log("database connected");
})
.catch((err) => console.log(err));
// Redirect to app with shop parameter upon auth
ctx.redirect(`/?shop=${shop}&host=${host}`);
},
})
);
router.get("/customers", async (ctx, next) => {
// Logics to fetch customers
});
const handleRequest = async (ctx) => {
await handle(ctx.req, ctx.res);
ctx.respond = false;
ctx.res.statusCode = 200;
};
router.get("(/_next/static/.*)", handleRequest); // Static content is clear
router.get("/_next/webpack-hmr", handleRequest); // Webpack content is clear
router.get("(.*)", verifyRequest(), handleRequest);
server.use(router.allowedMethods());
server.use(router.routes());
server.listen(port, () => {
console.log(`> Ready on http://localhost:${port}`);
});
});
index.js
require("#babel/register")({
presets: ["#babel/preset-env"],
ignore: ["node_modules"],
compact: false,
});
// Import the rest of our application.
module.exports = require("./server.js");
package.json
{
"name": "shopify-app-node",
"version": "1.0.0",
"description": "Shopify's node app for CLI tool",
"scripts": {
"lint": "next lint",
"test": "mocha",
"dev": "cross-env NODE_ENV=development nodemon ./server/index.js --watch ./server/index.js",
"build": "NEXT_TELEMETRY_DISABLED=1 next build",
"start": "cross-env NODE_ENV=production node ./server/index.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Shopify/shopify-app-node.git"
},
"author": "Shopify Inc.",
"license": "MIT",
"bugs": {
"url": "https://github.com/shopify/shopify-app-node/issues"
},
"dependencies": {
"#babel/core": "7.12.10",
"#babel/polyfill": "^7.6.0",
"#babel/preset-env": "^7.12.11",
"#babel/register": "^7.12.10",
"#shopify/app-bridge-react": "^2.0.6",
"#shopify/app-bridge-utils": "^2.0.6",
"#shopify/dates": "^1.1.5",
"#shopify/koa-shopify-auth": "^5.0.3",
"#shopify/polaris": "^6.2.0",
"#szhsin/react-menu": "^3.0.1",
"apollo-boost": "^0.4.9",
"axios": "^0.26.0",
"cross-env": "^7.0.3",
"date-fns": "^2.28.0",
"dotenv": "^8.6.0",
"fs": "^0.0.1-security",
"graphql": "^14.5.8",
"isomorphic-fetch": "^3.0.0",
"jquery": "^3.6.0",
"koa": "^2.13.1",
"koa-router": "^10.0.0",
"koa-session": "^6.1.0",
"mdb-react-ui-kit": "^3.0.0",
"moment": "^2.29.1",
"mongodb": "^4.5.0",
"mongoose": "^6.2.9",
"next": "^12.0.8",
"next-env": "^1.1.1",
"node-fetch": "^2.6.1",
"path": "^0.12.7",
"react": "^17.0.2",
"react-apollo": "^3.1.3",
"react-beautiful-dnd": "^13.1.0",
"react-csv": "^2.2.2",
"react-data-table-component": "^7.4.7",
"react-datepicker": "^4.7.0",
"react-dnd": "^16.0.1",
"react-dnd-html5-backend": "^16.0.1",
"react-dom": "^17.0.2",
"react-moment": "^1.1.1",
"react-router": "^6.2.2",
"react-router-dom": "^6.2.2",
"react-table": "^7.7.0",
"read-json-lines-sync": "^2.2.0",
"recharts": "^2.1.9",
"rsuite": "^5.7.1",
"styled-components": "^5.3.5",
"url": "^0.11.0",
"webpack": "^5.70.0"
},
"devDependencies": {
"#babel/plugin-transform-runtime": "^7.12.10",
"#babel/preset-stage-3": "^7.0.0",
"#wojtekmaj/enzyme-adapter-react-17": "^0.6.6",
"babel-jest": "26.6.3",
"babel-register": "^6.26.0",
"chai": "^4.3.6",
"chai-http": "^4.3.0",
"enzyme": "3.11.0",
"eslint": "^8.9.0",
"eslint-config-next": "^12.0.10",
"husky": "^4.3.6",
"jest": "26.6.3",
"lint-staged": "^10.5.4",
"mocha": "^10.0.0",
"nodemon": "^2.0.7",
"prettier": "2.2.1",
"react-addons-test-utils": "15.6.2",
"react-test-renderer": "16.14.0",
"supertest": "^6.2.4"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,css,json,md}": [
"prettier --write"
]
}
}

process is defined well from bootstrap.js but undefined inside the react code

I`m working on Nodejs app, which includes Front-end react that calls back-end api (Typescript).
The app is working great in development; but not in production.
When creating the production build, the front-end works fine and the back-end also started fine when running it using these commands on different Terminals:
sudo node server/main.js
sudo node bootstrap.js
However; When running the production build, I checked the "process" & "process.env" in the browser inspect tools, and they are returning normal values at the bootstrap file; but they are both returning "undefined" inside the react code blocks (which are build within the "build" folder located at the project root).
I have the files (.env, bootstrap.js, package.json) all at the project root.
.env code
# --- SERVER ---
HTTPS_CERT_PATH=./cert/backend/localhost.crt
HTTPS_KEY_PATH=./cert/backend/localhost.key
SERVER_PORT=3000
# --- REPORT ---
HTTPS_CERT_PATH=./cert/backend/localhost.crt
HTTPS_KEY_PATH=./cert/backend/localhost.key
REPORT_PORT=3001
# --- UI-CLIENT ---
CLIENT_PORT=4000
CLIENT_HTTPS_CERT_PATH=./cert/frontend/localhost.crt
CLIENT_HTTPS_KEY_PATH=./cert/frontend/localhost.key
# Change to 'https' if server certificates are specified
# Also, the port should be same as in the SERVER_PORT variable
API_SERVER_HOST=http://localhost:3000
API_REPORT_HOST=http://localhost:3001
# --- DO NOT CHANGE. CONTACT THE SUPPORT IF REQUIRED ---
PUBLIC_URL=
RSYSLOG_PORT=514
DATABASE_PORT=5433
LOG_FOLDER=./_docker/
APP_LOG_FOLDER=./_logs
ENABLE_SYSLOG_LISTENER=true
SSH_CONNECTION_DEBUG=false
ENABLE_RAM_LOG=false
REACT_APP_VALIDATION_URL=/api
REACT_APP_REPORT_URL=/api1
bootstrap code
const { createProxyMiddleware } = require('http-proxy-middleware')
const express = require('express');
const request = require('request');
const https = require('https');
const fs = require('fs');
const path = require('path');
require('dotenv').config();
const CLIENT_PORT = process.env.CLIENT_PORT || 4000;
const VALIDATION_API_URL = process.env.REACT_APP_VALIDATION_URL;
const REPORT_API_URL = process.env.REACT_APP_REPORT_URL;
const API_SERVER_HOST = process.env.API_SERVER_HOST;
const API_REPORT_HOST = process.env.API_REPORT_HOST;
const PUBLIC_URL = process.env.PUBLIC_URL;
const HTTPS_CERT_PATH = process.env.CLIENT_HTTPS_CERT_PATH;
const HTTPS_KEY_PATH = process.env.CLIENT_HTTPS_KEY_PATH;
const app = express();
var proxyapi = createProxyMiddleware('/api', { target: 'http://localhost:3000', changeOrigin: true });
var proxyapi1 = createProxyMiddleware('/api1', { target: 'http://localhost:3001', changeOrigin: true });
console.log(process.env);
app.use(VALIDATION_API_URL, (req, res) => {
const proxyUrl = API_SERVER_HOST + VALIDATION_API_URL + req.originalUrl.split(VALIDATION_API_URL)[1]
console.log("Original url:" + req.originalUrl);
console.log("Proxying to:" + proxyUrl + "\n");
req.pipe(request({url: proxyUrl, rejectUnauthorized: false})).pipe(res)
})
app.use(REPORT_API_URL, (req, res) => {
const proxyUrl = API_REPORT_HOST + REPORT_API_URL + req.originalUrl.split(REPORT_API_URL)[1]
console.log("Original url:" + req.originalUrl);
console.log("Proxying to:" + proxyUrl + "\n");
req.pipe(request({url: proxyUrl, rejectUnauthorized: false})).pipe(res)
})
app.use(PUBLIC_URL, express.static(path.join(__dirname, 'build')));
app.get(`${PUBLIC_URL}/*`, (req, res) => {
console.log("Request: " + req.originalUrl)
res.sendFile(path.join(__dirname, 'build', 'index.html'));
})
let options;
try {
options = {
cert: fs.readFileSync(HTTPS_CERT_PATH),
key: fs.readFileSync(HTTPS_KEY_PATH)
};
} catch (e) {
console.warn('Unable to create https access. Error while certificate reading: ' + e);
}
if (options) {
https.createServer(options, app).listen(CLIENT_PORT);
console.log(`Application listening at https://localhost:${CLIENT_PORT}${PUBLIC_URL}`)
} else {
app.listen(CLIENT_PORT, () => {
console.log(`Application listening at http://localhost:${CLIENT_PORT}${PUBLIC_URL}`)
});
}
package.json code
{
"name": "octopus-var",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "Octopus Cybersecurity INC.",
"scripts": {
"start": "node server/main",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage"
},
"dependencies": {
"#nestjs/common": "^7.5.1",
"#nestjs/core": "^7.5.1",
"#nestjs/event-emitter": "^1.0.0",
"#nestjs/jwt": "^7.2.0",
"#nestjs/passport": "^7.1.5",
"#nestjs/platform-express": "^7.5.1",
"#nestjs/schedule": "^0.4.3",
"#nestjs/typeorm": "^7.1.5",
"archiver": "^5.3.0",
"bcrypt": "^5.0.1",
"blob-stream": "^0.1.3",
"chart.js": "^3.5.0",
"chartjs-node-canvas": "^3.2.0",
"crypto-js": "^4.0.0",
"csv-parse": "^4.15.4",
"dotenv": "^10.0.0",
"http": "0.0.1-security",
"http-proxy-middleware": "^2.0.4",
"image-size": "^1.0.0",
"javascript-obfuscator": "^2.19.0",
"js2xmlparser": "^4.0.1",
"jsencrypt": "^3.2.0",
"logform": "^2.2.0",
"moment": "^2.29.1",
"nest-winston": "^1.5.0",
"node-html-to-image": "^3.2.0",
"node-pty": "^0.10.1",
"node-ssh": "^12.0.1",
"nodemailer": "^6.7.0",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"pdfkit": "^0.12.1",
"pg": "^8.5.1",
"phantom": "^6.3.0",
"read-last-lines": "^1.8.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.6.3",
"ssh2": "^0.8.9",
"ssh2shell": "^1.9.8",
"systeminformation": "^5.9.9",
"typeorm": "^0.2.30",
"uuid": "^8.3.2",
"winston": "^3.3.3",
"winston-daily-rotate-file": "^4.5.5",
"xlsx": "^0.17.0",
"xml2js": "^0.4.23"
},
"devDependencies": {
"#nestjs/cli": "^7.5.1",
"#nestjs/schematics": "^7.1.3",
"#nestjs/testing": "^7.5.1",
"#types/cron": "^1.7.2",
"#types/express": "^4.17.8",
"#types/jest": "^26.0.15",
"#types/node": "^14.14.6",
"#types/passport-jwt": "^3.0.4",
"#types/passport-local": "^1.0.33",
"#types/supertest": "^2.0.10",
"#typescript-eslint/eslint-plugin": "^4.6.1",
"#typescript-eslint/parser": "^4.6.1",
"eslint": "^7.12.1",
"eslint-config-prettier": "7.2.0",
"eslint-plugin-prettier": "^3.1.4",
"jest": "^26.6.3",
"prettier": "^2.1.2",
"supertest": "^6.0.0",
"ts-jest": "^26.4.3",
"ts-loader": "^8.0.8",
"ts-node": "^9.0.0",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.1.3"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
Please help!

NodeJs send you need to enable javascript on certain request

I have a Nodejs API that sends responses to a react application.
When I send a request for user information on login, the request succeeds and I get back a proper response. The thing is after I sent an initial request to log in, I get back the this response.
You need to enable JavaScript to run this app.
This only happens in production. Locally it's fine. Even doing a production build locally works just fine. It's only when I deploy to my AWS containers.
Here is my API package.json
{
"name": "my-api",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "nodemon ./bin/www",
"prod": "sudo forever stopall && forever start ./bin/www",
"start": "node ./bin/www",
"seed": "node ./setup/seed.js"
},
"engines": {
"node": ">= 12.0.0"
},
"dependencies": {
"aws-sdk": "^2.738.0",
"bcryptjs": "^2.4.3",
"bluebird": "^3.7.2",
"body-parser": "^1.19.0",
"braintree": "^3.5.0",
"compression": "^1.7.4",
"connect-pg-simple": "^6.2.1",
"cookie-parser": "~1.4.4",
"cors": "^2.8.5",
"debug": "~2.6.9",
"express": "^4.16.4",
"express-session": "^1.17.1",
"file-type": "^14.7.1",
"formik": "^2.1.4",
"fs": "0.0.1-security",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"multiparty": "^4.2.2",
"nodemailer": "^6.6.2",
"nodemailer-smtp-transport": "^2.7.4",
"nodemon": "^2.0.4",
"pg": "^8.2.1",
"pg-hstore": "^2.3.3",
"pg-transaction": "^1.0.4",
"uuid": "^8.3.2",
"winston": "^3.3.3"
}
}
Here is my application API.
const httpProxy = require("http-proxy");
const https = require("https");
const fs = require("fs");
const appConfig = require("./config");
const appPath = `./app.${appConfig.isProduction ? "prod" : "dev"}`;
const logger = require("./utils/logger");
const app = require(appPath);
const apiProxy = httpProxy.createProxyServer();
const ACUTAL_API = process.env.ACTUAL_API || "http://localhost:8181";
app.set("x-powered-by", false);
app.all("/api/*", function (req, res) {
logger.info("reverse proxying to api");
console.log("reverse proxying");
apiProxy.web(req, res, { target: ACTUAL_API });
});
if (!appConfig.isProduction) {
app.listen(appConfig.port, () => {
logger.info(`Server started at: http://localhost:${appConfig.port}`);
});
} else {
https
.createServer(
{
/* Certificate Managed By AWS ACM */
key: fs.readFileSync("./certificates/localhost.key"),
cert: fs.readFileSync("./certificates/localhost.crt"),
passphrase: "",
},
app
)
.listen(appConfig.port);
}
Application API app.prod.js
const express = require("express");
const app = express();
const path = require("path");
const BUILD_DIR = path.join(__dirname, "../build/");
console.log(BUILD_DIR);
app.use(express.static(BUILD_DIR));
const HTML_FILE = path.join(BUILD_DIR, "index.html");
app.get("*", (req, res) => res.sendFile(HTML_FILE));
module.exports = app;
Application API Package.json
{
"name": "proxy-server",
"version": "1.0.0",
"description": "proxy server for web",
"main": "index.js",
"scripts": {
"start": "nodemon ./",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "YoMommasKrypton",
"license": "ISC",
"dependencies": {
"babel-register": "^6.26.0",
"body-parser": "^1.19.0",
"cookie-parser": "^1.4.5",
"express": "^4.17.1",
"express-http-proxy": "^1.6.2",
"glob": "^7.1.6",
"node-env-file": "^0.1.8",
"winston": "2.3.1"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}

I am getting cant not find module error on node.js

I am running nodemon index.js file via cmd.
Then I am getting Error: Cannot find module 'undefined/package.json'
I have installed all the modules and dependencies written in package.json file.
my Package.json file is -
{
"name": "whasq-api",
"version": "0.1.1",
"description": "whasq-api",
"engines": {
"node": ">=8.11.1"
},
"main": "index.js",
"scripts": {
"pretest": "standard --fix",
"test": "exit 0"
},
"author": "WhASQ",
"license": "ISC",
"dependencies": {
"#rduk/configuration": "^2.2.3",
"#rduk/errors": "^1.3.1",
"#rduk/logger": "^1.0.3",
"#rduk/logger-winston-loggly-factory": "0.1.0",
"#rduk/logger-winston-provider": "^1.0.4",
"#rduk/message-broker": "^2.4.0",
"#rduk/provider": "^3.1.3",
"#rduk/tasks-orchestrator": "^0.1.3",
"aws-sdk": "^2.256.1",
"axios": "^0.18.1",
"bcrypt": "^3.0.4",
"body-parser": "^1.18.2",
"csv": "^3.1.0",
"dotenv": "5.0.1",
"elasticsearch": "^14.2.2",
"express": "4.16.3",
"express-request-id": "^1.4.1",
"helmet": "^3.15.1",
"jsonwebtoken": "8.2.1",
"morgan": "^1.9.1",
"multer": "^1.3.1",
"orm": "^4.0.2",
"pg": "^7.4.1",
"react-s3-uploader": "^4.8.0",
"socket.io": "2.0.4",
"socketio-jwt": "4.5.0",
"standard": "11.0.1",
"swagger-express-mw": "0.7.0",
"winston": "2.4.0"
}
}
and my index.js file is -
'use strict'
const SwaggerExpress = require('swagger-express-mw')
const app = require('express')()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const jwt = require('socketio-jwt')
const middlewares = require('./lib/middlewares')
const logger = require('#rduk/logger')
const configuration = require('#rduk/configuration').load()
// const broker = require('#rduk/message-broker')
const serverSettings = configuration.settings.get('server')
const config = {
appRoot: __dirname, // required config
swaggerSecurityHandlers: {
Auth: require('./lib/middlewares/auth')
}
}
// process.env.AWS_ACCESS_KEY_ID = 'AKIAJQNQTBQGBVMOAHCA';
// process.env.AWS_SECRET_ACCESS_KEY = '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';
// app.use('/s3', require('react-s3-uploader/s3router')({
// bucket: "whasq.com-dev",
// region: 'eu-west-3', //optional
// signatureVersion: 'v4', //optional (use for some amazon regions: frankfurt and others)
// headers: {'Access-Control-Allow-Origin': '*'}, // optional
// ACL: 'private', // this is default
// uniquePrefix: true // (4.0.2 and above) default is true, setting the attribute to false preserves the original filename in S3
// }));
SwaggerExpress.create(config, (err, swaggerExpress) => {
if (err) { throw err }
middlewares.addTo(app)
swaggerExpress.register(app)
})
server.listen(serverSettings.port, () => {
logger.info(`server listening on port ${serverSettings.port}`)
})
// socket.io
io.use(jwt.authorize({
secret: serverSettings.secret,
handshake: true
}))
io.on('connection', (socket) => {
logger.info(`${socket.decoded_token.username} connected to caw`)
socket.join(socket.decoded_token.id)
socket.on('disconnect', () => {
socket.leave(socket.decoded_token.id)
logger.info(`${socket.decoded_token.username} disconnected from caw`)
})
socket.on('message', action => {
console.log(action)
})
})
// consume notifications queue
// broker.consume('notifications', io)
How to resolve this problem Error: Cannot find module 'undefined/package.json'

Require returns an empty object when using jest and supertest to test koa2

I am learning test, for now I using jest and supertest to test koa2 server, and I test features is login, but I always receive false when test login feature, I find the require returns an empty object in my controllers/users.js after long time debug, I don't know why and very confuse about that, because everything is OK when I really running the koa2 server, help, thanks.
Here is my code
user.spec.js
import server from "../../app.js"
import request from "supertest"
afterEach(() => {
server.close()
})
test("Failed to login if typing wrong name and password", async () => {
const response = await request(server)
.post("/auth/user")
.send({
name: "wrong",
password: "wrong"
})
expect(response.body.success).toBe(false)
})
test("Successed to login if typing right name and password", async () => {
const response = await request(server)
.post("/auth/user")
.send({
name: "rignt",
password: "right"
})
expect(response.body.success).toBe(true) // always received false
})
app.js
const Koa = require('koa')
const app = new Koa()
const router = require('koa-router')()
const bodyParser = require('koa-bodyparser')
const logger = require('koa-logger')
// const port = 4155
const port = 6155
const auth = require('./server/routes/auth')
const api = require('./server/routes/api')
const users = require('./server/models/users')
const path = require('path')
const serve = require('koa-static')
const mount = require('koa-mount')
const historyApiFallback = require('koa2-history-api-fallback')
// handle database
const objection = require('objection')
const Model = objection.Model
const Knex = require('knex')
const knexConfig = require('./server/config/knexfile')
// Initialize knex
const knex = Knex(knexConfig)
// Bind all Models to a knex instance
Model.knex(knex)
app.use(bodyParser())
app.use(logger())
app.use(async (ctx, next) => {
let start = new Date()
await next()
let ms = new Date() - start
console.log('%s %s - %s', ctx.method, ctx.url, ms)
})
app.on('error', (err, ctx) => {
console.log('server error', err)
})
// api for operate
router.use('/api', api.routes())
// auth for login
router.use('/auth', async (ctx, next) => {
let urlReg = /auth\/user$/
if(urlReg.test(ctx.url)) {
await next()
} else {
const { token } = ctx.request.body
if(global.userTokenObj[token] === undefined) {
const rs = await users.findToken(token)
if(rs.length > 0) {
global.userTokenObj[token] = 1
await next()
} else {
ctx.body = {
code: 1001,
msg: "no login"
}
}
} else {
await next()
}
}
})
router.use('/auth', auth.routes())
app.use(router.routes())
// avoid refesh 404
app.use(historyApiFallback())
// koa static
app.use(mount('/static', serve(path.resolve('static'))))
app.use(serve(path.resolve('dist')))
module.exports = app.listen(port, () => {
console.log(`Koa is listening in ${port}`)
})
// module.exports = app
routes/auth.js
const {
getUserInfo,
postUserAuth,
} = require('../controllers/users')
const {
postFileNode,
postReadFile,
postWriteFile,
postBuildCode,
postDownloadProject
} = require('../controllers/editCode')
const router = require('koa-router')()
router.get('/user/:id', getUserInfo)
router.post('/user', postUserAuth)
router.post('/fileNode', postFileNode)
router.post('/readFile', postReadFile)
router.post('/writeFile', postWriteFile)
router.post('/build', postBuildCode)
router.post('/download', postDownloadProject)
module.exports = router
controllers/users.js
const users = require('../models/users') **// return empty object**
const jwt = require('jsonwebtoken') **// return empty object**
global.userTokenObj = {};
const getUserInfo = async ctx => {
try {
const id = ctx.params.id
const result = await users.getUserById(id)
ctx.body = result
} catch (error) {
console.log(error)
ctx.body = `error is ${error} when get user info`
}
}
const postUserAuth = async ctx => {
try {
const data = ctx.request.body // post data from request.body
const userInfo = await users.getUserByName(data.name)
if (userInfo != null) {
if (userInfo.password != data.password) {
ctx.body = {
success: false,
code: 2,
info: 'wrong password'
}
} else {
const userToken = {
name: userInfo.username,
id: userInfo.id
}
const secret = 'autoactivity'
const token = jwt.sign(userToken, secret)
global.userTokenObj[token] = userInfo.id
const rs = await users.setTokenById(userInfo.id, token)
ctx.body = {
success: true,
code: 0,
info: 'OK',
token
}
}
} else {
ctx.body = {
success: false,
code: 1,
info: 'no users'
}
}
} catch (error) {
console.log(error)
ctx.body = `error is ${error} when post user auth`
}
}
module.exports = {
getUserInfo,
postUserAuth,
}
models/users.js
const Model = require('objection').Model
class Users extends Model {
// Table name is the only required property.
static get tableName () {
return 'users'
}
}
const getUserById = async id => {
try {
const userInfo = await Users.query().findById(id)
return userInfo
} catch (error) {
console.log(error)
return error
}
}
const getUserByName = async name => {
try {
const userInfo = await Users
.query()
.findOne({
username: name
})
return userInfo
} catch (error) {
console.log(error)
return error
}
}
const setTokenById = async (id, token) => {
try {
const result = Users
.query()
.update({token})
.where('id', id)
return result
} catch(error) {
return error
}
}
const findToken = async (token) => {
try {
const result = Users
.query()
.select()
.where('token', token)
return result
} catch(error) {
return error
}
}
module.exports = {
getUserById,
getUserByName,
setTokenById,
findToken
}
package.json
{
"name": "auto-activity",
"version": "1.0.0",
"description": "A Vue.js project",
"author": "shangwenlong652 <dxcqcv#gmail.com>",
"private": true,
"scripts": {
"update": "gulp",
"debugnode": "nodemon --inspect-brk app.js",
"start": "nodemon app.js",
"devserver": "node app.js",
"dev": "node build/dev-server.js",
"server": "pm2 start app.js --name 'auto-activity'",
"server:test": "pm2 start app.js --name 'test-auto-activity'",
"showpm2": "pm2 show auto-activity",
"showpm2:test": "pm2 show test-auto-activity",
"savepm2": "pm2 save",
"logspm2": "pm2 logs",
"restartpm2": "pm2 restart auto-activity",
"restartpm2:test": "pm2 restart test-auto-activity",
"listpm2": "pm2 ls",
"stoppm2": "pm2 stop auto-activity",
"stoppm2:test": "pm2 stop test-auto-activity",
"delpm2": "pm2 delete auto-activity",
"delpm2:test": "pm2 delete test-auto-activity",
"server:dev": "nodemon app.js",
"newMigrate": "knex migrate:make add_name_date_type_to_projects --knexfile=./server/config/knexfile.js",
"migrate": "knex --knexfile=./server/config/knexfile.js migrate:latest",
"rollback": "knex --knexfile=./server/config/knexfile.js migrate:rollback",
"build": "node build/build.js",
"test": "jest --forceExit --runInBand"
},
"jest": {
"verbose": true,
"testURL": "http://localhost/",
"moduleFileExtensions": [
"js"
],
"transform": {
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest",
"^.+\\.js$": "<rootDir>/node_modules/babel-jest"
},
"setupTestFrameworkScriptFile": "mock-local-storage",
"coverageDirectory": "coverage",
"collectCoverage": true,
"coverageReporters": [
"lcov",
"text"
],
"moduleNameMapper": {
"#/(.*)$": "<rootDir>/src/$1"
},
"snapshotSerializers": [
"<rootDir>/node_modules/jest-serializer-vue"
]
},
"dependencies": {
"archiver": "2.1.0",
"await-busboy": "^1.0.1",
"axios": "^0.16.2",
"graceful-fs": "^4.1.11",
"jsonwebtoken": "~8.3.0",
"knex": "~0.15.2",
"koa": "^2.3.0",
"koa-bodyparser": "^4.2.0",
"koa-logger": "^3.0.1",
"koa-mount": "~3.0.0",
"koa-router": "^7.2.1",
"koa-static": "~4.0.1",
"koa2-history-api-fallback": "0.0.5",
"lodash": "^4.17.4",
"mariasql": "^0.2.6",
"mysql": "^2.13.0",
"objection": "^0.8.5",
"recursive-copy": "^2.0.6",
"replacestream": "^4.0.3",
"rimraf": "^2.6.2",
"vue": "2.4.2",
"vue-codemirror": "^4.0.5",
"vue-color": "^2.4.0",
"vue-router": "^2.6.0",
"vue-tree-halower": "^1.5.4",
"vuetify": "^0.15.2",
"vuex": "^2.3.1"
},
"devDependencies": {
"autoprefixer": "^7.1.2",
"babel-core": "~6.26.3",
"babel-eslint": "^7.1.1",
"babel-helper-vue-jsx-merge-props": "^2.0.3",
"babel-jest": "~23.4.2",
"babel-loader": "^7.1.1",
"babel-plugin-array-includes": "^2.0.3",
"babel-plugin-istanbul": "^4.1.1",
"babel-plugin-syntax-jsx": "^6.18.0",
"babel-plugin-transform-object-assign": "^6.22.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-plugin-transform-vue-jsx": "^3.7.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-stage-2": "^6.22.0",
"babel-register": "^6.22.0",
"babel-runtime": "^6.26.0",
"chai": "^3.5.0",
"chalk": "^2.3.0",
"connect-history-api-fallback": "^1.3.0",
"copy-webpack-plugin": "^4.0.1",
"cross-env": "~5.2.0",
"cross-spawn": "^5.0.1",
"css-loader": "^0.28.0",
"cssnano": "^3.10.0",
"del": "^3.0.0",
"dotenv": "~6.0.0",
"eslint": "~5.2.0",
"eslint-config-standard": "^6.2.1",
"eslint-friendly-formatter": "^3.0.0",
"eslint-loader": "^1.7.1",
"eslint-plugin-html": "^3.0.0",
"eslint-plugin-promise": "^3.4.0",
"eslint-plugin-standard": "^2.0.1",
"eventsource-polyfill": "^0.9.6",
"express": "~4.16.3",
"extract-text-webpack-plugin": "^2.0.0",
"file-loader": "^0.11.1",
"friendly-errors-webpack-plugin": "^1.1.3",
"gulp": "~4.0.0",
"gulp-decompress": "^2.0.1",
"html-webpack-plugin": "^2.28.0",
"http-proxy-middleware": "~0.18.0",
"inject-loader": "^3.0.0",
"jest": "~23.4.2",
"jest-serializer-vue": "~2.0.2",
"lolex": "^1.5.2",
"mock-local-storage": "^1.0.5",
"opn": "^5.1.0",
"optimize-css-assets-webpack-plugin": "^2.0.0",
"ora": "^1.2.0",
"pm2": "~3.0.3",
"semver": "^5.3.0",
"shelljs": "^0.7.6",
"sinon": "^2.1.0",
"sinon-chai": "^2.8.0",
"stylus": "^0.54.5",
"stylus-loader": "^3.0.1",
"supertest": "~3.1.0",
"url-loader": "~1.0.1",
"vue-jest": "~2.6.0",
"vue-loader": "^12.1.0",
"vue-style-loader": "^3.0.1",
"vue-template-compiler": "2.4.2",
"vue-test-utils": "~1.0.0-beta.11",
"webpack": "^2.6.1",
"webpack-bundle-analyzer": "~2.13.1",
"webpack-dev-middleware": "^1.10.0",
"webpack-hot-middleware": "^2.18.0",
"webpack-merge": "^4.1.0"
},
"engines": {
"node": ">= 4.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}
.babelrc
{
"presets": [
["env", {
"modules": false,
"targets": {
"chrome": 42,
"firefox": 38,
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": ["transform-runtime", "transform-vue-jsx"],
"env": {
"test": {
"presets": [["env", { "targets": { "node": "current" }} ]] ,
"plugins": [
"istanbul",
"transform-object-assign",
"array-includes",
"transform-runtime"
]
}
}
}
and the project full code on bitbutck
You're trying to import server from app.js at the very first line of your test code!
import server from "../../app.js"
But in the app.js you're not exporting server constant. You should export server after you passing the app instance to http.createServer() method.
const server = http.createServer(app);
module.exports = server;
Then it should work!

Resources