I developed a app using react, mongodb, express, nodeJS. I am able to run the app perfectly in my desktop. I have run express & react on different ports. But this doesn't work when I deploy it to heroku.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var Schema = mongoose.Schema;
var session = require('express-session');
var cookieParser = require('cookie-parser');
var cors=require('cors');
//setup express app
const app = express();
app.use(cors());
//connect to mongodb
mongoose.connect(process.env.MONGODBURI);
mongoose.Promise = global.Promise;
//connect public folder
app.use(express.static('public'));
//bodyparser middleware
app.use(bodyParser.json());
//routes middleware
app.use(cookieParser())
app.use(session({secret: 'MySecret'}));
app.use('/userapi',require('./routes/userapi.js'));
app.use('/cde',require('./routes/cde.js'));
app.use('/efg',require('./routes/efg.js'));
//error handler middleware
app.use(function(err,req,res,next){
res.status(422).send({error: err.message});
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log('Express server listening on port', port)
});
package.json
{
"name": "vip",
"version": "0.1.0",
"private": true,
"dependencies": {
"afterglow": "0.0.3",
"afterglowplayer": "^1.1.0",
"axios": "^0.17.1",
"body-parser": "^1.18.2",
"cookie-parser": "^1.4.3",
"cookieparser": "^0.1.0",
"cors": "^2.8.4",
"express": "^4.16.2",
"express-session": "^1.15.6",
"foreman": "^2.0.0",
"fs": "0.0.1-security",
"gifffer": "^1.5.1",
"glamor": "^2.20.40",
"image-map-resizer": "^1.0.3",
"jquery": "^3.3.1",
"marked": "^0.3.12",
"mongoose": "^5.0.1",
"natural": "^0.5.6",
"react": "^16.2.0",
"react-data-menu": "^1.1.1",
"react-dom": "^16.2.0",
"react-gif": "^0.1.0",
"react-modal": "^3.1.13",
"react-scripts": "1.1.0",
"react-toastify": "^3.4.2",
"redux": "^3.7.2",
"shelljs": "^0.8.1",
"video-react": "^0.9.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"nodemon": "^1.14.12",
"react-router-dom": "^4.2.2"
}
}
I've pushed all the code to heroku and I've set the mongodb uri to mlab in heroku dashboard settings. When I request express it gives me a error
GET https://myappname.herokuapp.com/userapi/verifylogin?email=aa&password=aa 404 (Not Found)
createError.js:16 Uncaught (in promise) Error: Request failed with status code 404
at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)
userapi`
const express = require('express');
const router = express.Router();
const User = require('../models/Login');
const LoginSession = require('../models/LoginSession');
const server = require('../server');
//find a record matching username & Password
router.get('/verifylogin',function(req,res,next){
User.findOne({email:req.query.email,password:req.query.password}).then(function(sequence_data){
res.send(sequence_data);
});
});
module.exports = router;
`
I've gone through many other posts related, but didn't resolved it.
Related
Hi I am unable to deploy functions using firebase, I am getting the below error.
On trying to look at the logs could not find anything concrete.
If someone can please help me to resolve this issue.
Below are the necessary details.
error displayed :
Function failed on loading user code. This is likely due to a bug in the user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.
Functions deploy had errors with the following functions:
app(us-central1)
i functions: cleaning up build files...
Error: There was an error deploying functions
On running function:log got the below :
2022-09-15T08:09:56.119842Z ? app: at require (node:internal/modules/cjs/helpers:102:18)
2022-09-15T08:09:56.119851Z ? app: at Object.<anonymous> (/workspace/index.js:10:32)
2022-09-15T08:09:56.119860Z ? app: at Module._compile (node:internal/modules/cjs/loader:1105:14)
2022-09-15T08:09:56.119869Z ? app: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
2022-09-15T08:09:56.119877Z ? app: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-09-15T08:09:56.119893Z ? app: at Function.Module._load (node:internal/modules/cjs/loader:822:12)
2022-09-15T08:09:56.119902Z ? app: at Module.require (node:internal/modules/cjs/loader:1005:19)
2022-09-15T08:09:56.120112Z ? app: Could not load the function, shutting down.
2022-09-15T08:09:56.385832481Z E app: Function cannot be initialized. Error: function terminated. Recommended action: inspect logs for termination reason. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging
2022-09-15T08:09:56.573338Z E app: {"#type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{"code":3,"message":"Function failed on loading user code. This is likely due to a bug in the user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation."},"authenticationInfo":{"principalEmail":"akhilmodi1988#gmail.com"},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.UpdateFunction","resourceName":"projects/pixstory-biz/locations/us-central1/functions/app"}
2022-09-15T08:12:27.847972Z N app: {"#type":"type.googleapis.com/google.cloud.audit.AuditLog","authenticationInfo":{"principalEmail":"akhilmodi1988#gmail.com"},"requestMetadata":{"callerIp":"122.179.194.233","callerSuppliedUserAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15,gzip(gfe),gzip(gfe)","requestAttributes":{"time":"2022-09-15T08:12:27.950588Z","auth":{}},"destinationAttributes":{}},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.DeleteFunction","authorizationInfo":[{"resource":"projects/pixstory-biz/locations/us-central1/functions/app","permission":"cloudfunctions.functions.delete","granted":true,"authorizationLoggingOptions":{"permissionType":"ADMIN_WRITE"},"resourceAttributes":{}}],"resourceName":"projects/pixstory-biz/locations/us-central1/functions/app","request":{"name":"projects/pixstory-biz/locations/us-central1/functions/app","#type":"type.googleapis.com/google.cloud.functions.v1.DeleteFunctionRequest"},"resourceLocation":{"currentLocations":["us-central1"]}}
2022-09-15T08:12:30.436268Z N app: {"#type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{},"authenticationInfo":{"principalEmail":"akhilmodi1988#gmail.com"},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.DeleteFunction","resourceName":"projects/pixstory-biz/locations/us-central1/functions/app"}
2022-09-15T08:13:04.366285Z I undefined: {"#type":"type.googleapis.com/google.cloud.audit.AuditLog","authenticationInfo":{"principalEmail":"akhilmodi1988#gmail.com"},"requestMetadata":{"callerIp":"122.179.194.233","callerSuppliedUserAgent":"FirebaseCLI/11.8.0,gzip(gfe),gzip(gfe)","requestAttributes":{"time":"2022-09-15T08:13:04.714274Z","auth":{}},"destinationAttributes":{}},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl","authorizationInfo":[{"resource":"projects/pixstory-biz/locations/us-central1","permission":"cloudfunctions.functions.sourceCodeSet","granted":true,"authorizationLoggingOptions":{"permissionType":"ADMIN_WRITE"},"resourceAttributes":{}}],"resourceName":"projects/pixstory-biz/locations/us-central1","request":{"parent":"projects/pixstory-biz/locations/us-central1","#type":"type.googleapis.com/google.cloud.functions.v1.GenerateUploadUrlRequest"},"response":{"uploadUrl":"https://storage.googleapis.com/uploads-975633983912.us-central1.cloudfunctions.appspot.com/20dd78fd-5c6a-4b23-8d2a-abce039a468e.zip?GoogleAccessId=service-284892888168#gcf-admin-robot.iam.gserviceaccount.com&Expires=1663231384&Signature=o24h25y7yLfKyAzOs8jE8%2BRiXQs9KzeIU2unV6TMBFLYSccAmvzKGB3qk0ps2nXZL0EpBQSAXqhj9nFxTLOWA8AxmS4bD0Z1vBuMpbBNps8mI%2FeY1k5wPnpDdPupG7CLIm%2FHd6H8iXhuF7CTJ7V8C6x%2FIOQP1XiEdOduwoGbUF%2BL9JAn4OpR4JCThIOkCHUu1zkb2lO6otqsfj%2BIYWNQTIJom5c4NgvlzDLFq2sRm2IFSmXhMUa1DVJy7zUEIJVCEdJn1n9MoAQdKqNSC%2BZ5XQSl0uylK5wQI1SyCi%2F32SDEzUK4QZV45dy8XTI2rIOIwdjo7w9s%2BadPzeeDVcN%2FqA%3D%3D","#type":"type.googleapis.com/google.cloud.functions.v1.GenerateUploadUrlResponse"},"resourceLocation":{"currentLocations":["us-central1"]}}
2022-09-15T08:13:04.706769Z I undefined: {"#type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{},"authenticationInfo":{"principalEmail":"akhilmodi1988#gmail.com"},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl","resourceName":"projects/pixstory-biz/locations/us-central1"}
2022-09-15T08:13:06.711244Z N app: {"#type":"type.googleapis.com/google.cloud.audit.AuditLog","authenticationInfo":{"principalEmail":"akhilmodi1988#gmail.com"},"requestMetadata":{"callerIp":"122.179.194.233","callerSuppliedUserAgent":"FirebaseCLI/11.8.0,gzip(gfe),gzip(gfe)","requestAttributes":{"time":"2022-09-15T08:13:07.105263Z","auth":{}},"destinationAttributes":{}},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.CreateFunction","authorizationInfo":[{"resource":"projects/pixstory-biz/locations/us-central1/functions/app","permission":"cloudfunctions.functions.create","granted":true,"authorizationLoggingOptions":{"permissionType":"ADMIN_WRITE"},"resourceAttributes":{}}],"resourceName":"projects/pixstory-biz/locations/us-central1/functions/app","request":{"location":"projects/pixstory-biz/locations/us-central1","function":{"entryPoint":"app","name":"projects/pixstory-biz/locations/us-central1/functions/app","httpsTrigger":{"securityLevel":"SECURE_ALWAYS"},"dockerRegistry":"ARTIFACT_REGISTRY","runtime":"nodejs16","labels":{"deployment-tool":"cli-firebase"},"sourceUploadUrl":"https://storage.googleapis.com/uploads-975633983912.us-central1.cloudfunctions.appspot.com/20dd78fd-5c6a-4b23-8d2a-abce039a468e.zip?GoogleAccessId=service-284892888168#gcf-admin-robot.iam.gserviceaccount.com&Expires=1663231384&Signature=o24h25y7yLfKyAzOs8jE8%2BRiXQs9KzeIU2unV6TMBFLYSccAmvzKGB3qk0ps2nXZL0EpBQSAXqhj9nFxTLOWA8AxmS4bD0Z1vBuMpbBNps8mI%2FeY1k5wPnpDdPupG7CLIm%2FHd6H8iXhuF7CTJ7V8C6x%2FIOQP1XiEdOduwoGbUF%2BL9JAn4OpR4JCThIOkCHUu1zkb2lO6otqsfj%2BIYWNQTIJom5c4NgvlzDLFq2sRm2IFSmXhMUa1DVJy7zUEIJVCEdJn1n9MoAQdKqNSC%2BZ5XQSl0uylK5wQI1SyCi%2F32SDEzUK4QZV45dy8XTI2rIOIwdjo7w9s%2BadPzeeDVcN%2FqA%3D%3D"},"#type":"type.googleapis.com/google.cloud.functions.v1.CreateFunctionRequest"},"resourceLocation":{"currentLocations":["us-central1"]}}[![enter image description here][1]][1]
index.js
const functions = require("firebase-functions");
// const admin = require('firebase-admin');
// admin.initializeApp();
const express = require('express');
//require('./db/mongoose');
require('../db/mongoose');
//const notification = require('./db/models/notification');
var bodyParser = require('body-parser');
const app = express();
const userprofileInformation = require('../routers/userprofileinfo');
const userCampaigninformation = require('../routers/userProjectInformation');
const searchPerson = require('../routers/search');
const filter = require('../routers/filter');
const multer = require('multer');
const jwt = require('jsonwebtoken');
const http = require('http').createServer(app);
let fs = require('fs');
const loginDetails = require('../routers/login_page');
//const jwt = require('jsonwebtoken');
const UserController = require('../routers/user_controller');
require('dotenv').config();
const filterPage = require('../routers/filter');
var cors = require("cors");
var cookieParser = require('cookie-parser');
var path = require('path');
const controller = require('../controllers/razorpay_controller');
const excelToJson = require('convert-excel-to-json');
const userProfile = require('../models/search');
const issueRaiseUser = require('../routers/user_issue');
app.use(cors());
const portCheck = process.env.PORT || 3001
app.use(express.json({limit: "50mb"}));
app.use(express.urlencoded({limit: "50mb", extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '../pix/public-flutter')));
app.get('/', (_, res) => {
res.sendFile(path.resolve(__dirname, '../pix/public-flutter/index.html'));
});
app.use(UserController);
app.use(userprofileInformation);
app.use(userCampaigninformation);
app.use(filter);
app.use(issueRaiseUser);
//app.use(searchPerson);
exports.app = functions.https.onRequest(app);
package.json
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "16"
},
"main": "index.js",
"dependencies": {
"bcryptjs": "^2.4.3",
"convert-excel-to-json": "^1.7.0",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"firebase-admin": "^10.0.2",
"firebase-functions": "^3.18.0",
"JSONStream": "^1.3.5",
"jsonwebtoken": "^8.5.1",
"mongoose": "^6.3.1",
"mongoose-sequence": "^5.3.1",
"multer": "^1.4.4",
"n": "^9.0.0",
"natural": "^5.2.3",
"node-nlp": "^4.24.0",
"nodemailer": "^6.7.5",
"otp-generator": "^4.0.0",
"razorpay": "^2.8.1",
"remove-stopwords": "^1.0.3",
"stable": "^0.1.8",
"stopword": "^2.0.2",
"stripe": "^9.11.0",
"twilio": "^3.78.0",
"validator": "^13.7.0"
},
"devDependencies": {
"firebase-functions-test": "^0.2.0"
},
"private": true
}
File structure:
[![Files][2]][2]
[2]: https://i.stack.imgur.com/6BGj7.png
I've been trying to deploy my Express application on Heroku and the build gets created successfully but when I try to open it, I'm greeted with an error message that basically states that the page could not be served.
So, I run heroku logs --tail and then I get the following error messages :
One half of the error messages
Remaining half of the error messages
File Tree
Procfile
web: node server.js
Package.json
{
"name": "conduit-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"nodemon": "^2.0.12",
"pg": "^8.7.1",
"pg-hstore": "^2.3.4",
"redux-persist": "^6.0.0",
"sequelize": "^6.6.5"
},
"devDependencies": {
"cross-env": "^7.0.3"
}
}
server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { sequelize } = require('./src/entities/User/User');
const db = require('./src/config/Database');
const feedRoute = require('./src/routes/Feed/Feed');
const usersRoute = require('./src/routes/Users/Users');
const userRoute = require('./src/routes/User/User');
const articlesRoute = require('./src/routes/Articles/Articles');
const profilesRoute = require('./src/routes/Profiles/Profiles');
const commentsRoute = require('./src/routes/Comments/Comments');
const app = express();
app.use(cors());
app.use(bodyParser.json());
// Routes
app.use('/api/feed', feedRoute);
app.use('/api/users', usersRoute);
app.use('/api/user', userRoute);
app.use('/api/articles', articlesRoute);
app.use('/api/profiles', profilesRoute);
app.use('/api/articles', commentsRoute);
// REQUESTS
app.get('/', async (req,res) => {
res.json('Yooooooooooo')
try {
await db.authenticate();
console.log('Connection has been established');
} catch(err) {
console.log('Error');
}
})
// To START sequelize and also wipes the DB clean
// async function main() {
// await sequelize.sync({force: true})
// }
// main()
// TO START sequelize
const PORT = process.env.PORT || 3000;
app.listen(PORT , () => {
console.log(`App is listening to ${PORT}`);
})
I've tried modifying my procfile and removing and re-installing the modules but the problem still persists.
I've been stuck on this for days now and any sort of help would be highly appreciated.
Looks like you problem is your pointing the main in package.json to a file that doesn't exist.
Package.json
"main": "index.js"
Your app seems to deploy from you server.js file.
The main field is a module ID that is the primary entry point to your program.
as per documentation: https://docs.npmjs.com/cli/v7/configuring-npm/package-json#main
I have made an app in react frontend and express as backend framework. These both are working fine in my local computer and when I have hosted Both server and client in Heroku they are deployed properly but when I am trying to login I am getting 405: Not allowed error.
When I am using the same server hosted in Heroku with the frontend hosted in my desktop it is working fine.
client : https://calm-fjord-20606.herokuapp.com/login
server : https://recorder-server-pkr.herokuapp.com/user/login
I have gone through many of the solutions provided here and in GitHub but none of them clarified my doubt.
/server.js - server
const express = require("express");
var app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const db = require("./config/keys").mongoURI;
const passport = require("passport");
const cors = require("cors");
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => {
console.log("Mongoose connected");
})
.catch(err => console.log(err));
//body-parser
app.use(bodyParser.urlencoded({ extended: true }));
// parse application/json
app.use(bodyParser.json());
//passport middleware
app.use(passport.initialize());
var publicDir = require("path").join(__dirname, "/public");
app.use(express.static(publicDir));
//routes
require("./routes/api/user")(app);
require("./routes/verifyaccount")(app);
require("./routes/api/file")(app);
app.get("/", cors(),(req, res) => {
res.json({
post: {
"/user/register": "to register",
"/user/login": "to login",
"/file": "to upload file",
"/verifyaccount/email": "to verify email using otp",
"/verifyaccount/sms": "to verify sms otp",
"/sendVerificationCode": "to reset password or resend verification code",
"/reset/:secretToekn": "forgot password"
},
get: {
"/current": "current user",
"/file": "to fetch file"
}
});
});
//passport config
require("./config/passport")(passport);
const port = process.env.PORT || 5000;
app.listen(port, process.env.IP , () => {
console.log(`Server started at port ${port}`);
});
/package.json - from client
{
"name": "light-bootstrap-dashboard-react",
"version": "1.2.0",
"private": true,
"dependencies": {
"axios": "^0.18.0",
"bootstrap": "3.3.7",
"chartist": "^0.10.1",
"classnames": "^2.2.6",
"draft-js": "^0.10.5",
"draftjs-to-html": "^0.8.4",
"griddle-react": "^1.0.0",
"history": "^4.7.2",
"html-to-draftjs": "^1.4.0",
"jquery": "^3.4.1",
"jspdf": "^1.5.3",
"jwt-decode": "^2.2.0",
"lodash": "^4.17.11",
"mdbreact": "^4.15.0",
"moment": "^2.24.0",
"node-sass": "4.6.1",
"node-sass-chokidar": "0.0.3",
"npm-run-all": "4.1.2",
"react": "^16.8.4",
"react-bootstrap": "0.32.1",
"react-bootstrap-table-next": "^3.0.1",
"react-chartist": "^0.13.1",
"react-dom": "^16.8.4",
"react-draft-wysiwyg": "^1.13.2",
"react-google-maps": "9.4.5",
"react-notification-system": "0.2.17",
"react-redux": "^6.0.1",
"react-router-dom": "^4.3.1",
"react-scripts": "^2.1.8",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0"
},
"scripts": {
"build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
"watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
"start-js": "react-scripts start",
"start": "npm-run-all -p watch-css start-js",
"build": "npm run build-css && react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"proxy": "https://recorder-server-pkr.herokuapp.com",
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
Any help will be appreciated. Thank you
Use cors middleware on server.
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
There are two ways:
You must enable cors in Back-end. (You can search Google as cors express )
You can use proxy in Front-end
I am trying to setup webpack dev server using webpackDevMiddleware, webpackHotMiddleware with express generator and react. I got everything working, but there's a huge delay in the reload.
I will get this message every time in the browser
'GET http://localhost:8080/__webpack_hmr
net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 (OK)'
But 5 to 10 seconds later the browser will reload. In the terminal, these messages are showing
GET /7310e23232f92e879547.hot-update.json 404 6.282 ms - 1573
GET / 304 1.071 ms - -
GET /__webpack_hmr 200 1.767 ms - -
GET /stylesheets/style.css 304 1.306 ms - -
GET /app-bundle.js 200 5.337 ms - 2960039
I think the express server has a delay or stopping from getting the hot-update.json.
I have tried time out and keepAliveTimeout the bin/www file
server.listen(port, () => {
server.timeout = 0
server.keepAliveTimeout = 0
});
package.json
{
"name": "react-webpack-hmr",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"dev": "nodemon ./bin/www --inspect --watch app.js --watch webpack.config.js --watch src",
"build": "webpack --config=webpack.config.js",
"clean": "rimraf public/dist"
},
"dependencies": {
"babel-loader": "^8.0.4",
"cookie-parser": "~1.4.3",
"css-loader": "^2.1.0",
"debug": "~2.6.9",
"ejs": "~2.5.7",
"ejs-loader": "^0.3.1",
"express": "~4.16.0",
"extract-loader": "^3.1.0",
"file-loader": "^3.0.1",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"http-errors": "~1.6.2",
"morgan": "~1.9.0",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"react-hot-loader": "^4.6.3",
"style-loader": "^0.23.1"
},
"devDependencies": {
"#babel/preset-react": "^7.0.0",
"#babel/runtime": "^7.2.0",
"#babel/generator": "^7.2.2",
"#babel/polyfill": "^7.2.5",
"babel-plugin-async-to-promises": "^1.0.5",
"#babel/core": "^7.2.2",
"#babel/plugin-transform-runtime": "^7.2.0",
"#babel/preset-env": "^7.2.3",
"webpack": "^4.28.3",
"webpack-cli": "^3.1.2",
"webpack-dev-middleware": "^3.4.0",
"webpack-dev-server": "^3.1.14",
"webpack-hot-middleware": "^2.24.3"
}
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
entry: {
app: [
'webpack-hot-middleware/client?reload=true',
// 'webpack/hot/only-dev-server',
// 'react-hot-loader/patch',
"#babel/runtime/regenerator",
"./src/app.js"
]
},
mode: 'development',
output: {
filename: "[name]-bundle.js",
path: path.join(__dirname, 'public/dist'),
publicPath: "/"
},
devtool: "cheap-eval-source-map",
devServer: {
contentBase: "dist",
overlay: true,
hot: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader'
}
]
},
{
test: /\.html$/,
use: [
{
loader: "html-loader"
}
]
},
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new HtmlWebpackPlugin({
template: './views/index.ejs'
})
]
}
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const webpack = require("webpack");
const config = require("./webpack.config");
const compiler = webpack(config);
const webpackDevMiddleware = require('webpack-dev-middleware')(compiler, config.devServer);
const webpackHotMiddleware = require('webpack-hot-middleware')(compiler, config.devServer);
var app = express();
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(webpackDevMiddleware);
app.use(webpackHotMiddleware);
//app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// 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 : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
React side app.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.js';
import { AppContainer } from 'react-hot-loader';
function render(Component) {
ReactDOM.render(
<AppContainer>
<Component />
</AppContainer>,
document.getElementById('app')
)
}
render(App);
if (module.hot) {
module.hot.accept('./components/App', () => {
const newApp = require('./components/App').default
render(newApp);
})
}
I expect the browser will reload after is finished compiling the new code without a delay everytime I save my files.
So I fixed it was my package.json
I was watching the react files which it shouldn't
I removed the old code this is the new one
"dev": "nodemon --inspect --watch webpack.config.js --watch app.js",
TLDR; In order to have hot module reload working with Nodemon you need to exclude the client code from watch.
Webpack uses __webpack_hmr to receive events about changes in code. If you edit a file then save it, Nodemon restarts and in this time Webpack HMR loses connection to the event stream, resulting in a miss for getting updated code. This is the reason why you need to exclude client side code from the watch list of Nodemon. Basically client side code refresh is 'managed' by Webpack dev server.
Usually I have a nodemon.json file in my root to let Nodemon know what to watch:
{
"watch": [
"server.js",
"src/server",
"config"
]
}
Trying to deploy and run Next.js on Azure Web App. Azure Web App works when running just with Express.js but as soon as I call nex() it fails. Tried to enable the error logging in Azure portal but not much of any use came out, just generic 500 errors.
Below is what works and what doesn't.
Works:
var express = require('express');
var expressServer = express();
expressServer.get('/', function (req, res) {
res.send('Express is working on IISNode!');
});
expressServer.listen(process.env.PORT || 8080);
Does not work:
var express = require('express');
const next = require('next');
var expressServer = express();
var app = next();
expressServer.get('/', function (req, res) {
res.send('Express is working on IISNode!');
});
expressServer.listen(process.env.PORT || 8080);
I don't even bother getting request handler at this point as the app = next() is failing.
Package.json:
"engines": {
"node": "9.4.0 || 8.9.x"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.2",
"next": "^4.2.3",
"next-redux-wrapper": "^1.3.5",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-redux": "^5.0.6",
"redux": "^3.7.2",
"redux-thunk": "^2.2.0"
},
"devDependencies": {
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"nodemon": "^1.14.11"
}
EDIT:
I believe the issue is that next build needs to run first. I am looking if I can add some post deployment/build command with something like Kudu. If you have any suggestions please let me know.
You are right, you need to run next build first.
So, this would work in Azure Web App if you create pages directory under project root and edit the package.json to add this:
"scripts": {
"postinstall": "next build"
}