I have an Angular app that is talking to a REST service.
When I run the Angular app local with the CLI, correctly proxies all /api requests to the REST service. When I try to build the app and run through a server.js (so that I can deploy the app to Heroku) I lose the proxy routing.
The REST service is deployed on Heroku and runs fine.
I run the Angular with:
ng serve
My proxy.conf.json
{
"/api": {
"target": "https://my-app.herokuapp.com",
"secure": true,
"changeOrigin": true
}
}
I created a server.js as described in this article so that I can deploy onto Heroku.
// server.js
const express = require('express');
const app = express();
const path = require('path');
// If an incoming request uses
// a protocol other than HTTPS,
// redirect that request to the
// same url but with HTTPS
const forceSSL = function () {
return function (req, res, next) {
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect(
['https://', req.get('Host'), req.url].join('')
);
}
next();
}
}
// Instruct the app
// to use the forceSSL
// middleware
app.use(forceSSL());
// Run the app by serving the static files
// in the dist directory
app.use(express.static(__dirname + '/dist'));
// For all GET requests, send back index.html
// so that PathLocationStrategy can be used
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname + '/dist/index.html'));
});
// Start the app by listening on the default
// Heroku port
app.listen(process.env.PORT || 4200);
I also set up a post install build in my package.json scripts:
{
"name": "catalog-manager-client",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "node server.js",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"postinstall": "ng build --aot"
},
"private": true,
"dependencies": {
"#angular/animations": "^6.0.3",
"#angular/cdk": "^6.2.1",
"#angular/cli": "~6.0.8",
"#angular/language-service": "^6.0.3",
"#angular/common": "^6.0.3",
"#angular/compiler": "^6.0.3",
"#angular/compiler-cli": "^6.0.3",
"#angular/core": "^6.0.3",
"#angular/flex-layout": "^6.0.0-beta.16",
"#angular/forms": "^6.0.5",
"#angular/http": "^6.0.3",
"#angular/material": "^6.2.1",
"#angular/platform-browser": "^6.0.3",
"#angular/platform-browser-dynamic": "^6.0.3",
"#angular/router": "^6.0.3",
"#swimlane/ngx-charts": "^8.0.2",
"#swimlane/ngx-datatable": "^13.0.1",
"core-js": "^2.5.4",
"express": "^4.16.4",
"hammerjs": "^2.0.8",
"jquery": "^3.3.1",
"moment": "^2.22.2",
"ngx-perfect-scrollbar": "^6.2.0",
"ngx-quill": "^3.2.0",
"rxjs": "^6.0.0",
"rxjs-compat": "^6.2.1",
"rxjs-tslint": "^0.1.4",
"zone.js": "^0.8.26"
},
"devDependencies": {
"#angular-devkit/build-angular": "~0.6.8",
"typescript": "~2.7.2",
"#types/jasmine": "~2.8.6",
"#types/jasminewd2": "~2.0.3",
"#types/node": "~8.9.4",
"codelyzer": "~4.2.1",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~1.7.1",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.0",
"karma-jasmine": "~1.1.1",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.3.0",
"ts-node": "~5.0.1",
"tslint": "~5.9.1"
},
"engines": {
"node": "9.11.2",
"npm": "6.5.0"
}
}
I am an Angular novice so I could be making a fundamental mistake, but how do I modify the server.js to use the proxy.conf.json settings?
The explanation falls into the yes, you're making a fundamental mistake category, but I've seen enough similar questions that I thought an explanation might just help the next dev.
The Angular CLI is running a full http server. The Angular UI is fully compiled and the CLI is serving it as static content from the /dist directory.
The proxy.conf.json settings are for the Server run by the Angular CLI, it has nothing to do with your compiled code.
When you move from a local environment to something like Heroku you need a server to take the place of the Angular CLI. This is where all the examples of node.js and express come in. The simple server.js file they walk you through is enough to set up a basic static content server. And that's fine, because your Angular code is static content!
But if you need routing to a dynamic backend server via a proxy.conf.json, well, your simple static server doesn't know anything about that.
In my case, my backend server runs on Koa, so I added static routing to the Angular code.
const router = require('koa-router')();
const body = require('koa-body')({ text: false });
const send = require('koa-send');
const fs = require('fs');
/**
* Code about server routes ommited
*/
async function main(ctx, next) {
//All dynamic routes start with "/api"
if (/\/api\//.test(ctx.path)) {
try {
await next();
}
catch (error) {
if (error instanceof ApplicationError) {
logger.error(error, { data: error.data, stack: error.stack });
ctx.status = error.code;
} else {
ctx.status = 500;
logger.error(error.message, { stack: error.stack });
}
}
return;
} else {
//Not a dynamic route, serve static content
if ((ctx.path != "/") && (fs.existsSync('dist' + ctx.path))) {
await send(ctx, 'dist' + ctx.path);
} else {
await send(ctx, 'dist/index.html');
}
}
}
module.exports = app => {
app.use(main);
app.use(router.routes());
};
NOTE - this isn't a performant solution for any kind of high workload, but if you've got a very small project that doesn't justify spending resources setting up something more scalable, this will work until you get bigger.
Any One looking for Implementation of angular application using proxy api on heroku you can use WebpackDev Server and http-proxy-middleware in server.js
npm install http-proxy-middleware
npm install webpack webpack-dev-server
webpack.config.js
const path = require('path');
module.exports = {
entry:'./src/index.js',//no implemenation needed by default webpack verification
mode: 'development',
devServer: {
historyApiFallback: true,// handle 404 cannot get error after refreshing url
https: true,//secure the server
compress: true,//invalid header multiple url proxy
client: {
webSocketURL: 'ws://0.0.0.0:8080/ws',// handle Invalid header error in heroku port 8080 maps in server.js
},
static: {
directory: path.join(__dirname, '/dist/<app-name>'),
},
proxy: {
/** Same as proxy.conf.json or proxy.conf.js */
' /api1/*': {
target: 'https://<other-heroku-deployed-url>',
changeOrigin:true,
secure:false,
pathRewrite: {
'^/api1':'https://<other-heroku-deployed-url>/api1' },
},
' /api2/*': {
target: 'https://<other-heroku-deployed-url>',
changeOrigin:true,
secure:false,
pathRewrite: {
'^/api2':'https://<other-heroku-deployed-url>/api2' },
}
},
},
};
server.js
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
const Webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
/** this is custom js to help proxy in server.js*/
const webpackConfig = require('./webpack.config.js');
const compiler = Webpack(webpackConfig);
const devServerOptions = { ...webpackConfig.devServer, open: true };
const server = new WebpackDevServer(devServerOptions, compiler);
const runServer = async () => {
console.log('Starting server...');
await server.start();
};
runServer();
/** If you have error creating proxy <app-url> to localhost
* Heroku internally redirect the Server port 8080 .
* For that reason we need to open listener port(I used 3000 here) redirect
through http-proxy-middleware*/
app.use("/*", createProxyMiddleware(
{ target: "https://localhost:8080",
ws: true ,
changeOrigin: true,
secure:false,
router: {
'dev.localhost:3000': 'https://localhost:8080',
},}))
app.listen(process.env.PORT || 3000)
npm start or node server.js
Related
I'm having trouble getting a little proxy working with my React app. I'm trying to use a little express server to keep some API keys secret so that my application can make use of a 3rd party API (the github API to be specific). I have a small express app running that I can query to get the API keys out of a .env file and attach those keys to my request to the 3rd party API.
Presently, I am able to start the front-end application and the express app simultaneously, and I can query the express app and get a response using my browser.
I'm trying to configure webpack to proxy my requests through this express app. In my webpack.config.js file I have:
//
devServer: {
port: 8080,
proxy: {
'/api/**': {
target: 'http://localhost:3000',
secure: false,
changeOrigin: true
}
}
}
//
Front-end application is running on port 8080, and my Express app is running on port 3000, both on the localhost.
In my React App, for trying to test whether this proxy is being detected/used, I have the following in a component:
//
handleSubmit(event) {
event.preventDefault();
fetch('/api/secret')
.then(res => {
console.log('RES: ', res)
res.json()
})
.then(data => {
console.log("Data: ", data)
return JSON.stringify(data)
})
this.props.onSubmit(this.state.username)
}
//
The backend code is super simple at the moment, but here it is:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();
// Initialize app
const app = express();
const port = 3000;
// Configure
app.use(bodyParser.json())
app.use(cors())
app.get('/secret', (req, res) => {
res.status(200)
res.send({ aSecret: process.env.<API_KEY> })
})
app.listen(port, () => console.log(`App is running on port ${port}`))
In my package.json I have the following (relevant script and dependencies):
...
...
"start": "concurrently --kill-others \"webpack-dev-server\" \"npm run server\"",
"server": "nodemon server/index.js"
},
"babel": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
},
"dependencies": {
"prop-types": "^15.7.2",
"react": "^16.13.0",
"react-dom": "^16.13.0",
"react-icons": "^3.9.0"
},
"devDependencies": {
"#babel/core": "^7.8.7",
"#babel/preset-env": "^7.8.7",
"#babel/preset-react": "^7.8.3",
"babel-loader": "^8.0.6",
"body-parser": "^1.19.0",
"concurrently": "^5.1.0",
"cors": "^2.8.5",
"css-loader": "^3.4.2",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"html-webpack-plugin": "^3.2.0",
"nodemon": "^2.0.2",
"style-loader": "^1.1.3",
"svg-inline-loader": "^0.8.2",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
},
"proxy": "http://localhost:3000"
}
As you can see, in the component I'm (attempting to) making a request to api/secret and hoping to get back in the response the API key that I have stored in my .env.
When I query this route in my browser using fetch('http://localhost:3000/secret') I am able to access the API key successfully, so I know that when I run the npm run start script that both the React application and the Express application are starting up simultaneously.
When I click the button in my React component that sends a request to /api/secret I get the following output in the browser console (in keeping with the console logs I have in the react component at the moment):
I'm just not sure at this point what I'm doing wrong with the proxy configuration in the devServer webpack configuration.
I can see that the hostname is being automatically prepended to the /api/secret in the fetch within the React component.
Stated Goal: Webpack successfully detects the proxy server I'm using to server requests to the 3rd party (GitHub) API.
I apologize if this question is a repeat, I've spent several hours researching and fiddling with this configuration and have been unsuccessful in finding out how to configure this. This is my first attempt at spinning up a little proxy server as well. Thanks in advance for any help!
You need to return res.json()
handleSubmit(event) {
event.preventDefault();
fetch('/api/secret')
.then(res => {
console.log('RES: ', res)
return res.json()
})
.then(data => {
console.log("Data: ", data)
return JSON.stringify(data)
})
this.props.onSubmit(this.state.username)
}
I am facing some problems in my (Dockerized) Angular application.
During the loading on Edge/Firefox of my angular application all Request (RestApi) needed to fill my homepage don't arrive to my application. If I load the same page with Chrome all requests arrived and the page is then filled.
The server.js of my Angular application is:
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var http = require('http');
var https = require('https');
var cors = require('cors');
var mongoose = require('mongoose');
var qs = require('querystring');
var fs = require('fs');
const nodemailer = require('nodemailer');
var env = process.env.NODE_ENV;
// Node express server setup.
var app = express();
app.set('port', 4200);
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended : true
}));
app.use(express.json()); // to support JSON-encoded bodies
var server = https.createServer(proxyOption, app);
server.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
// redirect requests from HTTP to HTTPS
http.createServer(function (req, res) {
console.log('Redirect HTTP request to https://' + req.headers['host'] + req.url);
res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url });
res.end();
}).listen(80);
Is this a problem of CORS doesn't working properly?
I have also seen that is suggested to put the following value in the polyfills.ts file:
-----> (window as any).__Zone_enable_cross_context_check = true;
import 'zone.js/dist/zone'; // Included with Angular CLI.
Microsoft Edge
Here you can see that on Edge the same request loaded is not working and the header is empty, that sounds strange
Edge Console:
On Chrome :
Firefox:
Why Access-Control-Allow-Headers are only in Chrome and not present in Firefox? (same page)
Why the following code is not visible when I load with Edge/Firefox?
app.all("/db/config", function(req, res, next) {
console.log(req.method + ' ' + req.url); <--- Visible only with Chrome
processDbRequest(req, res, Config);
});
I am starting the application with the following command:
ng serve --host 0.0.0.0 --port 443 --public-host IP --ssl --ssl-key /run/secrets/secret.key --ssl-cert /run/secrets/secret.cert --proxy-config server.js --prod
What do you think?
Tks
Anyhow on Chrome there is the section (CORS) not visible in the headers of Edge/Firefox.
UPDATE
The Error visible in EDGE are:
Uncaught (in promise): Response with status: 0 for URL: null"
[object Error]: {description: "Uncaught (in promise): Response with status: 0 for URL: null", message: "Uncaught (in promise): Response with status: 0 for URL: null", promise: Object, rejection: Object, stack: "Error: Uncaught (in promise): Response with status: 0 for URL: null at M (https://<IP>/polyfills.126a602ce79d269ee3a3.js:1:14070) at M (https://<IP>/polyfills.126a602ce79d269ee3a3.js:1:13634) at Anonymous function (https://<IP>/polyfills.126a602ce79d269ee3a3.js:1:14864) at t.prototype.invokeTask (https://<IP>/polyfills.126a602ce79d269ee3a3.js:1:8720) at onInvokeTask (https://<IP>/main.962c274fd5e7aea50f8c.js:1:422471) at t.prototype.invokeTask (https://<IP>/polyfills.126a602ce79d269ee3a3.js:1:8720) at e.prototype.runTask (https://<IP>/polyfills.126a602ce79d269ee3a3.js:1:4000) at g (https://<IP>/polyfills.126a602ce79d269ee3a3.js:1:11104) at e.invokeTask (https://<IP>/polyfills.126a602ce79d269ee3a3.js:1:9950) at m (https://<IP>/polyfills.126a602ce79d269ee3a3.js:1:23265)"...}
Here package.json configuration:
{
"name": "elg-dash",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "export NODE_ENV=dev && ng serve --port 3000 --proxy-config server.js ",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"#angular/animations": "~7.2.0",
"#angular/common": "~7.2.0",
"#angular/compiler": "~7.2.0",
"#angular/core": "~7.2.0",
"#angular/forms": "~7.2.0",
"#angular/http": "^7.2.15",
"#angular/platform-browser": "~7.2.0",
"#angular/platform-browser-dynamic": "~7.2.0",
"#angular/router": "~7.2.0",
"#eds/vanilla": "^3.4.0",
"body-parser": "^1.19.0",
"core-js": "^2.5.4",
"cors": "^2.8.5",
"d3": "^5.12.0",
"dragula": "^3.7.2",
"express": "^4.17.1",
"mapbox-gl": "^1.4.1",
"microsoft-adal-angular6": "^1.3.0",
"mongoose": "^5.7.5",
"ng2-completer": "^3.0.2",
"ng2-datepicker": "^3.1.1",
"ng2-smart-table": "^1.5.0",
"ngx-permissions": "^7.0.3",
"nodemailer": "^6.3.1",
"rxjs": "~6.3.3",
"tslib": "^1.9.0",
"zone.js": "~0.8.26"
},
"devDependencies": {
"#angular-devkit/build-angular": "~0.13.0",
"#angular/cli": "~7.3.9",
"#angular/compiler-cli": "~7.2.0",
"#angular/language-service": "~7.2.0",
"#types/jasmine": "~2.8.8",
"#types/jasminewd2": "^2.0.8",
"#types/node": "~8.9.4",
"codelyzer": "~4.5.0",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.0.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~1.1.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.4.0",
"rxjs-compat": "~6.5.3",
"ts-node": "~7.0.0",
"tslint": "~5.11.0",
"typescript": "~3.2.2"
}
}
SMALL UPDATE
It seems that the same angular application works in Firefox with the following version : 72.0.1 (64-bit), the same app doesn't work on the Linux Version 72.0.1 (64-bit).
#Prisco It is hard to say it is CORS because in that case you cannot get 200 OK status.
Your image do not give any hint much. I GUESS some scenarios happened to you base on my experience that I faced same issue before with Angular on server using JBOSS (not docker).
Check the response and see there is the message like failed to load... or not?
If yes, then something block your response. It could be your web server and could be your computer software like antivirus.
Check your page look like? Empty page? If Yes, It is because your front-end configuration like polyfill and browserlist.
Compare line by line to see different between Chrome and Edge to see any different and google it.
Could you try to deploy your project without docker to see it work or not. If it is working, then your docker configuration have issue.
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'm trying to deploy my reactjs (first) app on heroku, but i'm getting some trouble to get it online. I have no builds error, but when i try to launch my app i'm getting the "Cannot get /" error.
So on the Heroku logs i'm not getting any errors but only the heroku[routers] info with a 404 satus.
I did verify that my dist folder is not in .gitignore, try to add heroku logger (without success), add some code to package.json, server.json and webpack.config.js (without success).
my package.json (only important part) :
"engines": {
"node": "9.7.0",
"npm": "5.6.0"
},
"dependencies": {
"#material-ui/core": "^3.9.3",
"axios": "^0.17.1",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.9",
"dotenv": "^5.0.0",
"express": "^4.16.2",
"extract-text-webpack-plugin": "^3.0.2",
"faker": "^4.1.0",
"heroku": "^7.24.4",
"html-webpack-plugin": "^2.30.1",
"logger": "0.0.1",
"material-ui": "^0.20.2",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-draggable": "^3.3.0",
"react-img-zoom": "^0.1.0",
"react-magnifier": "^3.0.1",
"react-router-dom": "^5.0.0",
"react-tap-event-plugin": "^3.0.2",
"reactjs-popup": "^1.4.1",
"style-loader": "^0.19.1",
"twilio": "^3.28.0",
"twilio-video": "^1.15.2",
"webpack": "^3.12.0",
"webpack-dev-middleware": "^2.0.4",
"webpack-hot-middleware": "^2.21.0"
},
"scripts": {
"build": "./node_modules/.bin/webpack",
"start": "node server",
"start:prod": "npm run build && node server.js"
},
my webpack.config.js :
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require("webpack");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const path = require("path");
require("dotenv").config();
var configFunc = function(){
var config = {
devtool: "source-map",
entry: [
__dirname + "/app/app.js"
],
output: {
path: __dirname + "/dist",
filename: "bundle.js",
publicPath: "/"
},
module: {
rules: [
{
test: /\.js$/,
use: "babel-loader",
exclude: [/node_modules/]
},
{
test: /\.(sass|scss|css)$/,
use: [
{
loader: "style-loader" // creates style nodes from JS strings
},
{
loader: "css-loader" // translates CSS into CommonJS
}
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
hash: true,
template: path.join(__dirname , "/app/index.html"),
inject: "body"
}),
new webpack.BannerPlugin("React Twilio"),
new ExtractTextPlugin("[name]-[hash].css")
]};
if(process.env.NODE_ENV === "PROD") {
config.plugins.push(new webpack.optimize.UglifyJsPlugin());
config.plugins.push(new webpack.optimize.CommonsChunkPlugin({
name: "commons",
filename: "commons.js"
}));
}
if(process.env.NODE_ENV === "DEV") {
config.entry.push('webpack-hot-middleware/client?reload=true');
config.plugins.push(new webpack.HotModuleReplacementPlugin());
}
return config;
}();
module.exports = configFunc;
my server.js :
require("dotenv").config();
var path = require("path");
var express = require("express");
var webpack = require("webpack");
var faker = require("faker");
var AccessToken = require("twilio").jwt.AccessToken;
var VideoGrant = AccessToken.VideoGrant;
var app = express();
if(process.env.NODE_ENV === "DEV") { // Configuration for development environment
var webpackDevMiddleware = require("webpack-dev-middleware");
var webpackHotMiddleware = require("webpack-hot-middleware");
var webpackConfig = require("./webpack.config.js");
const webpackCompiler = webpack(webpackConfig);
app.use(webpackDevMiddleware(webpackCompiler, {
hot: true
}));
app.use(webpackHotMiddleware(webpackCompiler));
app.use(express.static(path.join(__dirname, "app")));
} else if(process.env.NODE_ENV === "PROD") { // Configuration for production environment
app.use(express.static(path.join(__dirname, "dist")));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});
}
app.use(function(req, res, next){
console.log("Request from: ", req.url);
next();
})
// Endpoint to generate access token
app.get("/token", function(request, response) {
var identity = faker.name.findName();
// Create an access token which we will sign and return to the client,
// containing the grant we just created
var token = new AccessToken(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_API_KEY,
process.env.TWILIO_API_SECRET
);
// Assign the generated identity to the token
token.identity = identity;
const grant = new VideoGrant();
// Grant token access to the Video API features
token.addGrant(grant);
// Serialize the token to a JWT string and include it in a JSON
response
response.send({
identity: identity,
token: token.toJwt()
});
});
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log("Express server listening on *:" + port);
});
and my Procfile :
web: npm run start:prod
You can find my app at this link : https://salty-dawn-74805.herokuapp.com/
For information my app is inspired by this tutorial : https://www.twilio.com/blog/2018/03/video-chat-react.html
You can clone this repository to reproduce : https://github.com/kimobrian/TwilioReact.git
The only error message i get is this (and obviously my website is working well on localhost):
heroku[router]: at=info method=GET path="/" host=salty-dawn-74805.herokuapp.com request_id= fwd= dyno=web.1 connect=1ms service=20ms status=404 bytes=383 protocol=https
Hope someone can help me, i'm new to reactjs and it's the first time i'm deploying a reactjs app.
Thank you very much,
Solution found for others who maybe will have the same error !
It was really stupide : heroku node_env is "production" and i was verifying node_env equals "prod". :'(
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"
]
}