I am getting cant not find module error on node.js - 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'

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"
]
}
}

How to use a Postgres db on heroku with Axios and Vue?

I making a spa with Vue and want to deploy this on Heroku and provision a database with Postgres.
I managed to get the app to run on Heroku, with a node server. I added the db and the connection (in the same file) and it is working in production.
But I want to make the HTTP-request to de the db with Axios and test this locally before deployment. And this is where I'm stuck.
I've copied the DATABASE_URL the a .env, but still no access to the database. When I print the value to the console it is always undefined.
My server.js:
const express = require("express");
const serveStatic = require("serve-static");
const path = require("path");
const port = process.env.PORT || 8080;
// Connection to the database
const { Client } = require('pg');
const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
});
client.connect();
client.query('SELECT table_schema,table_name FROM information_schema.tables;', (err, res) => {
if (err) throw err;
for (let row of res.rows) {
console.log(JSON.stringify(row));
}
client.end();
});
//
const app = express();
//here we are configuring dist to serve app files
app.use("/", serveStatic(path.join(__dirname, "/dist")));
// this * route is to serve project on different page routes except root `/`
app.get(/.*/, function (req, res) {
res.sendFile(path.join(__dirname, "/dist/index.html"));
});
app.listen(port);
console.log(`app is listening on port: ${port}`);
UserService.js:
import axios from 'axios';
// the single Axios instance we use for calls
const apiClient = axios.create({
//baseURL: 'http://localhost:5000',
baseURL: process.env.DATABASE_URL, // with ssl?
withCredentials: false, // this is the default
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
export default {
/* with pagination */
getUsers() {
console.log(process.env.DATABASE_URL);
return apiClient.get('/users');
},
};
package.json:
{
"name": "test-deploy-heroku",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"start": "node server.js"
},
"dependencies": {
"axios": "^0.21.1",
"core-js": "^3.6.5",
"dns": "^0.2.2",
"express": "^4.17.1",
"pg": "^8.5.1",
"pg-native": "^3.0.0",
"vue": "^2.6.11",
"vue-router": "^3.2.0",
"vuetify": "^2.4.0",
"vuex": "^3.4.0"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-plugin-router": "~4.5.0",
"#vue/cli-plugin-vuex": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"#vue/eslint-config-prettier": "^6.0.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-prettier": "^3.3.1",
"eslint-plugin-vue": "^6.2.2",
"prettier": "^2.2.1",
"sass": "^1.32.0",
"sass-loader": "^10.0.0",
"vue-cli-plugin-vuetify": "~2.3.1",
"vue-template-compiler": "^2.6.11",
"vuetify-loader": "^1.7.0"
}
}
I copied the config vars to my local .env file
heroku config:get CONFIG-VAR-NAME -s >> .env
And the started the process with
heroku local
But I still can not connect to the db with axios.
I searched all over, but didn't find an answer.
You may need to add require('dotenv').config() to the top of your server.js file
if (process.env.NODE_ENV === 'development') require('dotenv').config()

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

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!

Trying to send simple data from server to react native client-side

I am trying to send data from server.js using express and node.js to my client-side which is in React Native, both sides work individually but aren't communicating with each other. I am fairly new to backend development so I am beginning to understand how it functions and how to implement required behaviors. Please can anyone help?
server.js
const express = require('express')
const app = express()
const port = process.env.PORT || 5000;
app.get('/', (req, res) => {
res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' })
}
)
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
app.js
import React, { Component } from "react";
import {Modal, StyleSheet, View, StatusBar,Text, ActivityIndicator, FlatList} from 'react-native'
export default class FetchExample extends React.Component {
constructor(props){
super(props);
this.state = {
data: ''
};
}
componentDidMount() {
// Call our fetch function below once the component mounts
this.callBackendAPI()
.then(res => this.setState({ data: res.express }))
.catch(err => console.log(err));
}
// Fetches our GET route from the Express server. (Note the route we are fetching matches the GET route from server.js
callBackendAPI = async () => {
const response = await fetch('/');
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
render(){
return(
<View style={{flex: 1, paddingTop:20}}>
<Text>{this.state.data}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
});
package.Json
{
"name": "mapp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"#expo/vector-icons": "^10.0.2",
"babel-plugin-mobx-deep-action": "^1.6.1",
"express": "^4.17.1",
"jetifier": "^1.6.3",
"jsc-android": "241213.x.x",
"mobx": "^5.11.0",
"mobx-react": "^6.1.1",
"native-base": "^2.13.8",
"react": "16.8.3",
"react-native": "^0.59.10",
"react-native-background-fetch": "^2.6.0",
"react-native-background-geolocation": "^3.0.7",
"react-native-css-gradient": "^0.3.1",
"react-native-drop-down-item": "^1.0.5",
"react-native-dropdown-menu": "^2.0.0",
"react-native-elements": "^1.2.6",
"react-native-gesture-handler": "^1.3.0",
"react-native-input-scroll-view": "^1.9.3",
"react-native-ionicons": "^4.5.6",
"react-native-linear-gradient": "react-native-community/react-native-linear-gradient",
"react-native-maps": "^0.24.2",
"react-native-responsive-screen": "^1.2.2",
"react-native-svg": "^9.5.2",
"react-native-svg-transformer": "^0.13.0",
"react-native-vector-icons": "^6.5.0",
"react-native-vertical-tab-view": "^0.1.3",
"react-navigation": "^3.11.0",
"react-redux": "^7.1.0",
"redux": "^4.0.1"
},
"devDependencies": {
"#babel/core": "7.4.5",
"#babel/plugin-proposal-decorators": "^7.4.4",
"#babel/runtime": "7.4.5",
"babel-jest": "24.8.0",
"babel-preset-react-native": "4.0.0",
"jest": "24.8.0",
"metro-react-native-babel-preset": "0.54.1",
"react-test-renderer": "16.8.3",
"redux-devtools": "^3.5.0"
},
"jest": {
"preset": "react-native"
},
"proxy": "http://localhost:5000/"
try updating the url to the full url of your local server:
const response = await fetch('http://localhost:5000');
Check the port matches your express server port ^^

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