I'm trying to clone whatsapp.. I've done with frontend part.. but when I try to connect with mongodb and get & post a request through postman api... but my code is getting crashed.
I'm using "type":"module" in package.json
This is what i'm getting in terminal
Listening on localhost:9000
D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongodb\lib\connection_string.js:282
throw new error_1.MongoParseError(`${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported`);
^
MongoParseError: option usecreateindex is not supported
at parseOptions (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongodb\lib\connection_string.js:282:15)
at new MongoClient (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongodb\lib\mongo_client.js:45:63)
at D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\connection.js:802:16
at new Promise (<anonymous>)
at Connection.openUri (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\connection.js:799:19)
at D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\index.js:409:10
at D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\index.js:1262:10) {
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v18.13.0
[nodemon] app crashed - waiting for file changes before starting...
import express from 'express';
import mongoose from 'mongoose';
import Messages from './dbMessages.js';
const app = express();
const port = process.env.PORT || 9000;
app.use(express.json());
const connection_url = 'mongodb+srv://sarath_babayaga:Sarath#1996#cluster0.wzoouq0.mongodb.net/clone-whatsapp-backend? retryWrites=true&w=majority'
mongoose.connect(connection_url,{
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true
})
app.get('/',(req,res)=>res.status(200).send('hello world!!!!'));
app.get('/messages/sync', (req, res) => {
const dbMessage = req.body
Messages.find ((err, data) => {
if (err) {
res.status(500).send(err)
} else {
res.status(200).send(data)
}
})
})
app.post('/messages/new', (req, res) => {
const dbMessage = req.body
Messages.create(dbMessage, (err, data) => {
if (err) {
res.status(500).send(err)
} else {
res.status(201).send(data)
}
})
})
app.listen(port,()=>console.log(`Listening on localhost:${port}`));
according to the official forum of MongoDB, UseCreateIndex is deprecated since Mongoose 6, so I think this is the issue. Try removing useCreateIndex from your code
https://www.mongodb.com/community/forums/t/option-usecreateindex-is-not-supported/123048/3
I am not able to set up Forest Admin with my local environment (Express and MySQL). When I try to authenticate, I am getting 404 for /forest/authentication route.
app.js
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const jwt = require('express-jwt');
const Sequelize = require('sequelize');
const forest = require('forest-express-sequelize');
const { errorHandler } = require('forest-express-sequelize');
// const { createAgent } = require('#forestadmin/agent');
// const {
// createSequelizeDataSource,
// } = require('#forestadmin/datasource-sequelize');
require('dotenv').config();
const cors = require('cors');
const sequelizeInstance = require('./src/db/models/index').sequelize;
var indexRouter = require('./src/routes/index');
var authRouter = require('./src/routes/api/auth');
var usersRouter = require('./src/routes/api/users');
var ceremonyRouter = require('./src/routes/api/ceremony');
var questionRouter = require('./src/routes/api/questions');
var app = express();
let allowedOrigins = [
/\.forestadmin\.com$/,
/localhost:\d{4}$/,
'http://localhost:6868',
];
var corsOptions = {
origin: allowedOrigins,
maxAge: 86400, // NOTICE: 1 day
credentials: true,
};
// Support for request-private-network as the `cors` package
// doesn't support it by default
// See: https://github.com/expressjs/cors/issues/236
app.use((req, res, next) => {
if (req.headers['access-control-request-private-network']) {
res.setHeader('access-control-allow-private-network', 'true');
}
next(null);
});
app.use(
'/forest/authentication',
cors({
...corsOptions,
// The null origin is sent by browsers for redirected AJAX calls
// we need to support this in authentication routes because OIDC
// redirects to the callback route
origin: corsOptions.origin.concat('null'),
})
);
app.use(cors(corsOptions));
// view engine setup
app.set('views', path.join(__dirname, 'src/views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//Routes
app.use('/', indexRouter);
app.use('/api', indexRouter);
app.use('/api/auth', authRouter);
app.use('/api/users', usersRouter);
app.use('/api/ceremony', ceremonyRouter);
app.use('/api/questions', questionRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
// set port, listen for requests
const PORT = process.env.NODE_DOCKER_PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
// // Create your Forest Admin agent
// // This must be called BEFORE all other middlewares on the express app
// createAgent({
// authSecret: process.env.FOREST_AUTH_SECRET,
// agentUrl: process.env.FOREST_AGENT_URL,
// envSecret: process.env.FOREST_ENV_SECRET,
// isProduction: process.env.NODE_ENV === 'production',
// })
// .addDataSource(createSequelizeDataSource(sequelizeInstance))
// .mountOnExpress(app)
// .start();
app.use(
jwt({
secret: process.env.FOREST_AUTH_SECRET,
credentialsRequired: false,
algorithms: ['HS256'],
})
);
forest
.init({
envSecret: process.env.FOREST_ENV_SECRET,
authSecret: process.env.FOREST_AUTH_SECRET,
objectMapping: Sequelize,
connections: { default: sequelizeInstance },
})
.then((FAMiddleware) => {
app.use(FAMiddleware);
});
app.use(errorHandler());
module.exports = app;
package.json
{
"name": "backend",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"start_dev": "nodemon ./bin/www",
"docker": "docker-compose up --build"
},
"dependencies": {
"#forestadmin/agent": "1.0.0-beta.43",
"#forestadmin/datasource-sequelize": "1.0.0-beta.34",
"bcryptjs": "^2.4.3",
"cookie-parser": "~1.4.4",
"cors": "^2.8.5",
"date-and-time": "^2.4.1",
"debug": "~2.6.9",
"dotenv": "^16.0.1",
"express": "~4.16.1",
"express-jwt": "6.1.2",
"express-validator": "^6.14.2",
"forest-express-sequelize": "8.5.11",
"handlebars": "^4.7.7",
"handlebars-helpers": "^0.10.0",
"http-errors": "~1.6.3",
"jade": "^0.29.0",
"jsonwebtoken": "^8.5.1",
"mailgun.js": "^8.0.0",
"moment": "^2.29.4",
"morgan": "~1.9.1",
"mysql2": "^2.3.3",
"nodemailer": "^6.7.7",
"passport": "^0.6.0",
"passport-jwt": "^4.0.0",
"rand-token": "^1.0.1",
"sequelize": "^6.21.3",
"sequelize-auto": "^0.8.8"
},
"devDependencies": {
"nodemon": "^2.0.19",
"sequelize-cli": "^6.4.1"
}
}
docker-compose.yml
version: '3.8'
services:
mysqldb:
platform: linux/x86_64
image: mysql:8.0.29
restart: unless-stopped
env_file: ./.env
environment:
- MYSQL_ROOT_PASSWORD=$MYSQLDB_ROOT_PASSWORD
- MYSQL_DATABASE=$MYSQLDB_DATABASE
ports:
- $MYSQLDB_LOCAL_PORT:$MYSQLDB_DOCKER_PORT
volumes:
- db:/var/lib/mysql
phpmyadmin:
image: phpmyadmin/phpmyadmin
ports:
- 11819:80
depends_on:
- mysqldb
environment:
PMA_HOSTS: mysqldb
PMA_USER: $MYSQLDB_USER
PMA_PASSWORD: $MYSQLDB_ROOT_PASSWORD
UPLOAD_LIMIT: 100M
app:
depends_on:
- mysqldb
build:
context: .
network: host
restart: unless-stopped
env_file: ./.env
volumes:
- .:/var/www/app
working_dir: /var/www/app
ports:
- $NODE_LOCAL_PORT:$NODE_DOCKER_PORT
environment:
- DB_HOST=mysqldb
- DB_USER=$MYSQLDB_USER
- DB_PASSWORD=$MYSQLDB_ROOT_PASSWORD
- DB_NAME=$MYSQLDB_DATABASE
- DB_PORT=$MYSQLDB_DOCKER_PORT
stdin_open: true
tty: true
volumes:
db:
The Node.js project is running on localhost:6868 without any issues:
terminal log
andand#And-MacBook-Pro backend % docker-compose up --build
[+] Building 42.5s (10/10) FINISHED
=> [internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 32B 0.0s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> [internal] load metadata for docker.io/library/node:16 0.6s
=> [internal] load build context 0.5s
=> => transferring context: 2.11MB 0.5s
=> CACHED [1/6] FROM docker.io/library/node:16#sha256:1ed1e17ccabb09038cfb8a965337ebcda51ef9e9d32082164c502d 0.0s
=> [2/6] COPY package.json . 0.0s
=> [3/6] RUN npm install -g nodemon 3.6s
=> [4/6] RUN npm install 35.6s
=> [5/6] COPY . . 1.0s
=> exporting to image 1.1s
=> => exporting layers 1.1s
=> => writing image sha256:53f94f35be4528c5cd899f5702e433acf915a3b1d01a2dbdf098d35482a42bf5 0.0s
=> => naming to docker.io/library/backend_app 0.0s
Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them
[+] Running 3/3
â ŋ Container backend-mysqldb-1 Created 0.0s
â ŋ Container backend-app-1 Recreated 0.1s
â ŋ Container backend-phpmyadmin-1 Created 0.0s
Attaching to backend-app-1, backend-mysqldb-1, backend-phpmyadmin-1
backend-mysqldb-1 | 2022-08-09 14:22:50+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.29-1.el8 started.
backend-phpmyadmin-1 | AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.18.0.3. Set the 'ServerName' directive globally to suppress this message
backend-phpmyadmin-1 | AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.18.0.3. Set the 'ServerName' directive globally to suppress this message
backend-phpmyadmin-1 | [Tue Aug 09 14:22:51.704530 2022] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.53 (Debian) PHP/8.0.19 configured -- resuming normal operations
backend-phpmyadmin-1 | [Tue Aug 09 14:22:51.706056 2022] [core:notice] [pid 1] AH00094: Command line: 'apache2 -D FOREGROUND'
backend-mysqldb-1 | 2022-08-09 14:22:51+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
backend-app-1 | [nodemon] 2.0.19
backend-app-1 | [nodemon] to restart at any time, enter `rs`
backend-app-1 | [nodemon] watching path(s): *.*
backend-app-1 | [nodemon] watching extensions: js,mjs,json
backend-app-1 | [nodemon] starting `node /var/www/app/app.js npm run start_dev`
backend-mysqldb-1 | 2022-08-09 14:22:51+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.29-1.el8 started.
backend-mysqldb-1 | '/var/lib/mysql/mysql.sock' -> '/var/run/mysqld/mysqld.sock'
backend-mysqldb-1 | 2022-08-09T14:22:53.698645Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.29) starting as process 1
backend-mysqldb-1 | 2022-08-09T14:22:53.808611Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
backend-mysqldb-1 | 2022-08-09T14:22:53.846153Z 1 [ERROR] [MY-012585] [InnoDB] Linux Native AIO interface is not supported on this platform. Please check your OS documentation and install appropriate binary of InnoDB.
backend-mysqldb-1 | 2022-08-09T14:22:53.846650Z 1 [Warning] [MY-012654] [InnoDB] Linux Native AIO disabled.
backend-mysqldb-1 | 2022-08-09T14:22:54.473510Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
backend-mysqldb-1 | 2022-08-09T14:22:55.462049Z 0 [System] [MY-010229] [Server] Starting XA crash recovery...
backend-mysqldb-1 | 2022-08-09T14:22:55.478820Z 0 [System] [MY-010232] [Server] XA crash recovery finished.
backend-mysqldb-1 | 2022-08-09T14:22:55.754773Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
backend-mysqldb-1 | 2022-08-09T14:22:55.756819Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
backend-mysqldb-1 | 2022-08-09T14:22:55.774738Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
backend-mysqldb-1 | 2022-08-09T14:22:56.089136Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
backend-mysqldb-1 | 2022-08-09T14:22:56.091257Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.29' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server - GPL.
backend-app-1 | [forest] ðģðģðģ Your configDir ("/var/www/app/forest") does not exist. Please make sure it is set correctly.
backend-app-1 | Server is running on port 8080.
backend-app-1 | [forest] ðģðģðģ Checking need for apimap update...
backend-app-1 | Executing (default): SELECT 1+1 AS result
backend-app-1 | Connection has been established successfully.
backend-app-1 | [forest] ðģðģðģ No change in apimap, nothing sent to Forest.
backend-app-1 | POST /forest/authentication 404 315.425 ms - 1916
backend-app-1 | GET / 304 16.272 ms - -
backend-app-1 | GET /stylesheets/style.css 304 2.196 ms - -
db/models/index.js
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../../config/database.js')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], {
...config,
host: process.env.USING_DOCKER ? 'host.docker.internal' : config.host,
});
} else {
sequelize = new Sequelize(config.database, config.username, config.password, {
...config,
host: process.env.USING_DOCKER ? 'host.docker.internal' : config.host,
});
}
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch((err) => {
console.error('Unable to connect to the database:', err);
});
fs.readdirSync(__dirname)
.filter((file) => {
return (
file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js'
);
})
.forEach((file) => {
const model = require(path.join(__dirname, file))(
sequelize,
Sequelize.DataTypes
);
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
module.exports = db;
I tried to change:
app.use(
'/forest/authentication',
cors({
...corsOptions,
// The null origin is sent by browsers for redirected AJAX calls
// we need to support this in authentication routes because OIDC
// redirects to the callback route
origin: corsOptions.origin.concat('null'),
})
);
to this
const watchRouter = new express.Router();
watchRouter.post(
'/authentication',
cors({
...corsOptions,
// The null origin is sent by browsers for redirected AJAX calls
// we need to support this in authentication routes because OIDC
// redirects to the callback route
origin: corsOptions.origin.concat('null'),
})
);
app.use('/forest', watchRouter);
but it didn't help. I am still getting POST /forest/authentication 404.
I changed the code to this and it's working now:
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const { createAgent } = require('#forestadmin/agent');
const {
createSequelizeDataSource,
} = require('#forestadmin/datasource-sequelize');
require('dotenv').config();
const cors = require('cors');
const sequelizeInstance = require('./src/db/models/index').sequelize;
var indexRouter = require('./src/routes/index');
var authRouter = require('./src/routes/api/auth');
var usersRouter = require('./src/routes/api/users');
var ceremonyRouter = require('./src/routes/api/ceremony');
var questionRouter = require('./src/routes/api/questions');
var app = express();
// Create your Forest Admin agent
// This must be called BEFORE all other middlewares on the express app
createAgent({
authSecret: process.env.FOREST_AUTH_SECRET,
agentUrl: process.env.FOREST_AGENT_URL,
envSecret: process.env.FOREST_ENV_SECRET,
isProduction: process.env.NODE_ENV === 'production',
})
.addDataSource(createSequelizeDataSource(sequelizeInstance))
.mountOnExpress(app)
.start();
let allowedOrigins = [/\.forestadmin\.com$/, /localhost:\d{4}$/];
if (process.env.ALLOWED_CORS) {
allowedOrigins = allowedOrigins.concat(process.env.ALLOWED_CORS.split(','));
}
var corsOptions = {
origin: allowedOrigins,
};
app.use(cors(corsOptions));
// view engine setup
app.set('views', path.join(__dirname, 'src/views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//Routes
app.use('/', indexRouter);
app.use('/api', indexRouter);
app.use('/api/auth', authRouter);
app.use('/api/users', usersRouter);
app.use('/api/ceremony', ceremonyRouter);
app.use('/api/questions', questionRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
// set port, listen for requests
const PORT = process.env.NODE_DOCKER_PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
module.exports = app;
In locally the application works perfectly but when i deployed it on heroku it showing errors on heroku logs. Also data wasn't added in mongoDb database. Actually in the application i used google-oauth login so in locally it works perfectly but not in heroku. I've also whitelisted my ip on mongodb atlas but still can't figure out why this error getting.
Anybody help me plz.....
Here is my prod.js file
module.exports = {
googleClientID: process.env.GOOGLE_CLIENT_ID,
googleClientSecret: process.env.GOOGLE_CLIENT_SECRET,
mongoURI: process.env.MONGO_URI,
cookieKey: process.env.COOKIE_KEY
}
Here is my keys.js file
// Keys.js - figure out what credentials should return
if (process.env.NODE_ENV === "production") {
// So we are in prodution - return the prod set of keys
module.exports = require('./prod');
} else {
// We are developement - return the dev keys
module.exports = require('./dev');
}
Here is my index.js file
const express = require('express');
const mongoose = require('mongoose');
const passport = require('passport');
const cookieSession = require('cookie-session');
const keys = require('./config/keys');
require('./models/User');
require('./services/passport');
const app = express();
//Middleware
app.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000,
keys: [keys.cookieKey]
})
);
app.use(passport.initialize());
app.use(passport.session());
// mongoDb Connection
mongoose.connect(keys.mongoURI, {
useNewUrlParser: true
}).then(() => console.log('MongoDb Connect successfully'))
.catch(err => console.log(err));
// actual routes
require('./routes/authRoutes')(app);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server is running in ${PORT}`));
Actually i getting two different errors first was this
2019-09-02T06:28:59.760121+00:00 app[web.1]: Warning: connect.session() MemoryStore is not
2019-09-02T06:28:59.760149+00:00 app[web.1]: designed for a production environment, as it will leak
2019-09-02T06:28:59.760151+00:00 app[web.1]: memory, and will not scale past a single process.
2019-09-02T06:28:59.763577+00:00 app[web.1]:
2019-09-02T06:28:59.763581+00:00 app[web.1]: /app/node_modules/mongoose/lib/connection.js:519
2019-09-02T06:28:59.763583+00:00 app[web.1]: throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
2019-09-02T06:28:59.763585+00:00 app[web.1]: ^
2019-09-02T06:28:59.763838+00:00 app[web.1]: MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
2019-09-02T06:28:59.763842+00:00 app[web.1]: at new MongooseError (/app/node_modules/mongoose/lib/error/mongooseError.js:10:11)
2019-09-02T06:28:59.763844+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:519:11)
2019-09-02T06:28:59.763846+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:321:15)
2019-09-02T06:28:59.763848+00:00 app[web.1]: at Object.<anonymous> (/app/index.js:24:10)
2019-09-02T06:28:59.763850+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:701:30)
2019-09-02T06:28:59.763852+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
2019-09-02T06:28:59.763854+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:600:32)
And the second one is this
2019-09-02T08:49:22.115492+00:00 app[web.1]: { MongoNetworkError: failed to connect to server [productionproj-shard-00-00-qfouv.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to productionproj-shard-00-00-qfouv.mongodb.net:27017 closed]
So on...... as same as above
Here is my mongodb production url i've been added on heroku config vars
mongodb+srv://nansProdDeploy:nansProdDeploy#productionproj-qfouv.mongodb.net/test?retryWrites=true&w=majority
It's all about whitelisting the correct ip address. When we put our application on heroku we must whitelist the ip by clicking [ Allow Access From Anywhere ] button and then click ok your ip will be 0.0.0.0/0 this ip will allow to access your deployed heroku application. When you are using your application locally at that point of you have to choose [ Add Current Ip Address ] to access your application locally
I have a simple webpack with react hotloader & express setup and working. I'm trying to add an external node module that will register a sub router for some services. For some reason, doing so causes a strange exception (see below).
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config');
var app = express();
var router = express.Router();
var mod = require("my-module");
mod.registerServices(router); // <-- adds routes to the router
app.use("/api/v1*", router); // <-- This line causes the error
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
stats: {
colors: true
}
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(3000, 'localhost', function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://localhost:3000');
});
The Exception:
$ node server.js
/Users/bmonro/Documents/Code/nui-redux/node_modules/react-transform-hmr/lib/index.js:51
throw new Error('locals[0] does not appear to be a `module` object with Hot Module ' + 'replacement API enabled. You should disable react-transform-hmr in ' + 'production by using `env` section in Babel configuration. See the ' + 'example in README: https://github.com/gaearon/react-transform-hmr');
^
Error: locals[0] does not appear to be a `module` object with Hot Module replacement API enabled. You should disable react-transform-hmr in production by using `env` section in Babel configuration. See the example in README: https://github.com/gaearon/react-transform-hmr
at Object.proxyReactComponents [as default] (/Users/bmonro/Documents/Code/nui-redux/node_modules/react-transform-hmr/lib/index.js:51:11)
at Object.<anonymous> (/Users/bmonro/Documents/Code/nui-redux/src/ext/nui-company-admin/lib/CompanyLocation/components/simple.js:25:60)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/bmonro/Documents/Code/nui-redux/src/ext/nui-company-admin/lib/CompanyLocation/containers/CompanyLocationPage.js:13:25)
at Module._compile (module.js:434:26)
UPDATE
Turns out that removing this from .babelrc where I have some react transforms enabled and subsequently removing all of the web pack hotloader plugins & middleware gets the router working again.
{
"transform": "react-transform-hmr",
"imports": ["react"],
"locals": ["module"]
}
Try this solution: don't use babel-plugin-react-transform in .babelrc, use config in webpack.config.js
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loader: 'babel',
include: path.join(__dirname, 'src'),
query: {
plugins: [
["react-transform", {
transforms: [{
transform: "react-transform-hmr",
imports: ["react"],
locals: ["module"]
}]
}]
]
}
}
]
}
Details:
https://github.com/gaearon/babel-plugin-react-transform/issues/62
https://github.com/gaearon/react-transform-hmr/issues/5
I'm trying to set up Gulp to watch 1 thing: server's source. Upon source update, the server node script will start over & client browser will refresh.
I believe I need gulp-nodemon for the server, while browser-sync for the client.
The server's script is executed by: node src\babel.js
The script works when ran that way, but fails through my config for Gulp.
Is there something I am doing wrong?
This is my task script:
var gulp = require('gulp');
var browserSync = require('browser-sync');
var nodemon = require('gulp-nodemon');
gulp.task('default', ['watchServer', 'watchClient']);
gulp.task('watchServer', function() {
gulp.watch('src/**', function () {
nodemon({ // called upon update
script: 'src/babel.js', // I have tried both / & \\
})
});
nodemon({ // called on start
script: 'src/babel.js', // I have tried both / & \\
})
});
gulp.task('watchClient', function() {
browserSync({
open: 'external',
host: 'ââââââââ',
port: 80,
ui: false,
server: {
// We're serving the src folder as well
// for sass sourcemap linking
baseDir: ['src']
},
files: [
'src/**'
]
});
});
Log:
> gulp
[02:28:04] Using gulpfile B:\Test Server\gulpfile.js
[02:28:04] Starting 'watchServer'...
[02:28:04] Finished 'watchServer' after 19 ms
[02:28:04] Starting 'watchClient'...
[02:28:04] Finished 'watchClient' after 27 ms
[02:28:04] Starting 'default'...
[02:28:04] Finished 'default' after 9.66 Ξs
[02:28:04] [nodemon] 1.7.1
[02:28:04] [nodemon] to restart at any time, enter `rs`
[02:28:04] [nodemon] watching: *.*
[02:28:04] [nodemon] starting `node src\babel.js`
[BS] Access URLs:
-----------------------------------
Local: http://localhost:80
External: http://ââââââââ:80
-----------------------------------
[BS] Serving files from: src
[BS] Watching files...
events.js:141
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::80
at Object.exports._errnoException (util.js:837:11)
at exports._exceptionWithHostPort (util.js:860:20)
at Server._listen2 (net.js:1231:14)
at listen (net.js:1267:10)
at Server.listen (net.js:1363:5)
at B:/Test Server/src/app/app.jsx:17:7
at Object.<anonymous> (B:/Test Server/src/app/app.jsx:41:2)
at Module._compile (module.js:434:26)
at normalLoader (B:\Test Server\node_modules\babel-core\lib\api\register\node.js:199:5)
at Object.require.extensions.(anonymous function) [as .jsx] (B:\Test Server\node_modules\babel-core\lib\api\register\node.js:216:7)
[02:28:05] [nodemon] app crashed - waiting for file changes before starting...
You don't need to watch the server file with gulp since nodemon will automatically restart when it changes, try something like this in your config
gulp.task('watchServer', function() {
// remove the gulp.watch entry
nodemon({ // called on start
script: 'src/babel.js', // I have tried both / & \\
ext: 'js',
watch: ['src/babel.js']
})
});
There also seems to be something else running on port 80 (this is the default port for apache) so it might help to change the port browsersync is running on to something like 4000
If your node server is running on let's say port 3000 you will need to proxy it with browsersync for example.
gulp.task('watchClient', function() {
browserSync({
open: 'external',
host: 'ââââââââ',
proxy: '[YOURHOST]:3000'
port: 4000,
ui: false,
// this entry will most likely need to be removed
// if you are using something like express as a static server
server: {
// We're serving the src folder as well
// for sass sourcemap linking
baseDir: ['src']
},
files: [
'src/**'
]
});
});