I have worked code, which is built in /dist by webpack, for developming that is slow to wait for updating/building in dist/ folder and get result form it also. there is good "webpack-dev-server --port=4200" command but I have expressJS. How I can get updating result fast after run project. Maybe It is possable via webpack or not:
/////////////////////package.json
"scripts": {
"ng": "ng",
"dev": "concurrently nodemon ./src/index.ts \"tsc -w -p ./src\" ",
"start": "ng build && concurrently nodemon ./src/index.ts \"tsc -w -p ./src\" ",
"build": "ng build --watch",
"build:watch": "\"tsc -w -p ./src\"",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
//////////////////////index.ts
import * as express from 'express';
import { join } from 'path';
import { json, urlencoded }from 'body-parser';
var app : any = express();
app.use(express.static(join(__dirname + '/../dist')));
app.use(json());
app.use(urlencoded({
extended: true
}));
app.get('*', function(req, res, next) {
res.sendFile(join(__dirname + '/../dist/index.html'));
});
console.log('3000!! ', 3000);
app.listen(process.env.PORT || 3000);
I tried just to include ./src folder - app.use(express.static(resolve(__dirname, '../src'))); res.sendFile(resolve(__dirname, '../src/index.html')); but it is not working:
Help Please
packaje.json
dist
assets
src - app
- index.html
- index.ts
Related
I have a fullstack app I deployed on Heroku with React in the frontend and Node.js for my backend. Initially, my frontend would display but the server wasn't running. Now that I've added more dependencies in my package.json, it seems the server is running but the frontend won't render. My page looks like this:
When I look at the Heroku logs, this is what the output is:
It seems that the server is starting on a port (in this instance Port: 17789 and 46894) but then something else tries to run on the same port which causes an error. The port for my server is set to process.env.PORT in the index.js file on my backend. I'm not sure if this is what I need to change or not. Here is the index.js:
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
import postRoutes from './routes/posts.js';
const app = express();
//Middleware
app.use(bodyParser.json({ limit: '30mb', extended: true }));
app.use(bodyParser.urlencoded({ limit: '30mb', extended: true }));
app.use(cors());
app.use('/posts', postRoutes);
const CONNECTION_URL =
'mongodb+srv://caseyclinga:123abc#passport.czhpd.mongodb.net/recollections?retryWrites=true&w=majority';
const PORT = process.env.PORT || 5000;
mongoose
.connect(CONNECTION_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() =>
app.listen(PORT, () => console.log(`Server running on Port: ${PORT} `))
)
.catch((err) => console.log(err));
And lastly, here is my package.json:
{
"scripts": {
"build": "cd client && npm run build",
"install-client": "cd client && npm install",
"heroku-postbuild": "npm run install-client && npm run build",
"server": "cd server && nodemon server.js",
"develop": "concurrently --kill-others-on-fail \"npm run server\" \"npm run start --prefix client\"",
"start": "concurrently --kill-others-on-fail \"npm run server\" \"npm run start --prefix client\""
},
"dependencies": {
"body-parser": "^1.20.0",
"concurrently": "^7.2.1",
"cors": "^2.8.5",
"express": "^4.18.1",
"mongoose": "^6.3.4",
"nodemon": "^2.0.16"
}
}
Does anyone know where the issue may be in this?
In your code you have app.use('/posts', postRoutes);, but you are trying to get /post instead of /posts.
Hopefully, this will be my last question regarding NextJS.
I finally moved all of my React components to NextJS and I'm in the step of uploading it to Heroku.
The usual code for a React app looks like this:
if (
process.env.NODE_ENV === 'production' &&
process.env.NODE_TECHNOLOGY === `react`
) {
// This is for ReactJS
app.use(express.static(path.join(path.resolve(), 'client-app/build')))
app.get('*', (req, res) =>
res.sendFile(
path.resolve(path.resolve(), 'client-app', 'build', 'index.html')
)
)
} else {
app.get('/', (req, res) => {
res.status(200).json({
success: true,
data: 'API is running',
time: new Date().toISOString(),
})
})
}
I then tried adding an else-if statement for NextJS:
if (
process.env.NODE_ENV === 'production' &&
process.env.NODE_TECHNOLOGY === `react`
) {
// This is for ReactJS
app.use(express.static(path.join(path.resolve(), 'client-app/build')))
app.get('*', (req, res) =>
res.sendFile(
path.resolve(path.resolve(), 'client-app', 'build', 'index.html')
)
)
} else if (
process.env.NODE_ENV === 'production' &&
process.env.NODE_TECHNOLOGY === `next`
) {
app.use(express.static(path.join(path.resolve(), 'client-next-app/build')))
app.get('*', (req, res) =>
res.sendFile(
path.resolve(path.resolve(), 'client-next-app', 'build', 'index.html')
)
)
} else {
// This is for NextJS production
app.get('/', (req, res) => {
res.status(200).json({
success: true,
data: 'API is running',
time: new Date().toISOString(),
})
})
}
However, I'm still unsure what I am supposed to submit because after running the npm run build command, next returns this file structure:
I already modified my nextJS package.json file:
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start -p $PORT"
},
and this is what my top-folder package.json file looks like:
"scripts": {
"client-install": "npm install --prefix client",
"start": "NODE_ENV=production node server.js",
"server": "nodemon server.js",
"client-react": "npm start --prefix client-app",
"client-next": "npm run dev --prefix client-next-app",
"devreact": "concurrently \"npm run server\" \"npm run client-react\" \"npx peer --port PORT\" ",
"dev": "concurrently \"npm run server\" \"npm run client-next\" \"npx peer --port PORT\" ",
"debug": "ndb server",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client-next-app && npm run build --prefix client-next-app"
},
Any idea? Thanks.
I have a Front End application which is mainly based on React, and I have created a node server to serve the application. Build and everything are successful, and the the index.html is also served, but it doesn't read the environment variables that I set through heroku application settings (even from CLI).
Package.json scripts
"scripts": {
"start": "node server",
"start-dev": "react-scripts start",
"start-windows": "set PORT=3001 && react-scripts start",
"build": "react-scripts build",
"postinstall": "npm run build",
"test": "jest src/**/*.test.js",
"eject": "react-scripts eject"
}
node server,
const express = require ('express')
const app = express();
const http = require('http').Server(app);
const path = require( 'path')
let port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'build') + '/index.html');
});
app.listen(port, () => {
console.log(`App running on port ${port}`);
});
I print followings in a js,
console.log('LOCAL_TEST_ENVIRONMENT --- ', process.env.LOCAL_TEST_ENVIRONMENT) // LOCAL_TEST_ENVIRONMENT --- undefined
console.log('BACKEND_URL --- ', process.env.BACKEND_URL) // BACKEND_URL --- undefined
console.log('NODE_ENV --- ', process.env.NODE_ENV) // NODE_ENV --- production
Environment variables I set,
How can I fix this?
The prefix REACT_APP_ is necessary when accessing env variables, try
{process.env.REACT_APP_LOCAL_TEST_ENVIRONMENT}
I want to use process.env
-this is db.js-
import * as dotenv from "dotenv";
import mongoose from "mongoose";
dotenv.config();
const { DB_URL } = process.env.PRODUCTION ? process.env : "localhost:27017/save-idiot";
const { DB_PROTOCOL } =process.env.PRODUCTION ? process.env : "mongodb"
mongoose.connect(`${DB_PROTOCOL}://${DB_URL}`, {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
});
const db = mongoose.connection;
const handleOpen = () => console.log("✅ Connected to DB");
const handleError = error => console.log(`❌ Error on DB Connection:${error}`);
db.once("open", handleOpen);
db.on("error", handleError);
-package.json-
"scripts": {
"dev:server": "nodemon --exec babel-node src/init.js -- delay 2",
"dev:assets": "cd src && WEBPACK_ENV=development webpack -w",
"lint": "eslint src/",
"fix": "eslint --fix src/",
"clean": "rm -rf build",
"build:server": "babel src --out-dir build --ignore 'src/assets','src/static','src/webpack.config.js'",
"build:assets": "cd src && WEBPACK_ENV=production webpack",
"copy:static": "cp -R src/static src/views build/",
"build": "npm run clean && npm run lint && npm run build:server && npm run build:assets && npm run copy:static",
"start": "PRODUCTION=true forever start build/init.js"
}
const { DB_URL } = process.env.PRODUCTION ? process.env : "localhost:27017/save-idiot";
const { DB_PROTOCOL } =process.env.PRODUCTION ? process.env : "mongodb"
if I npm run dev:server,
I want to get "localhost:27017/save-idiot" & "mongodb"
and if I npm start,
I want to get process.env
How can I do this?
You could use cross-env package, it is used to set environment variables.
Once you've installed it, you could try like this:
"start": "cross-env PRODUCTION=true forever start build/init.js"
Try use
dotenv.config({ path: '.env' });
For configure many environments you can use envdist
Well, i have 3 types of environments (i.e development,test,production) am using nodejs with express. My problem is this my either development and production scripts don't run because they can't access .env variables i have searched online but i can't find something helpful. This is what i did i created .env file and put my variables in. i tried using export command i.e export key=value. please help
I created a .env file and added either of development database url and production database url, but when i run either of environment it doesn't work. i also tried using export command export key=value. but it works for a while and then it fails again.
//my config
require('dotenv').config();
module.exports ={
development :{
use_env_variable: process.env.DEVELOPMENT_URL,
dialect: 'postgres'
},
production :{
use_env_variable:process.env.PRODUCTION_URL,
dialect: 'postgres',
}
}
//my package.json scripts
{
"name": "report_deck",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "export NODE_ENV=production && sequelize db:migrate && node ./build/index.js",
"dev": "nodemon --exec babel-node ./api/index.js",
"test": "export NODE_ENV=test && sequelize db:migrate:undo:all && sequelize db:migrate && nyc --require #babel/register mocha ./api/test/test.js --timeout 20000 --exit",
"build": "rm -rf ./build && babel -d ./build ./api -s",
"generate-lcov": "nyc report --reporter=text-lcov > lcov.info",
"coveralls-coverage": "coveralls < lcov.info",
"codeclimate-coverage": "codeclimate-test-reporter < lcov.info",
"coverage": "nyc npm test && npm run generate-lcov && npm run coveralls-coverage && npm run codeclimate-coverage"
},
}
//.env
DEVELOPMENT_URL=postgres://example1:pass#example:5432/dbname
PRODUCTION_URL=postgres://example2:pass#example:5432/dbname
//my index.js
import express from 'express';
import bodyParser from 'body-parser';
import classRoutes from './server/routes/classRouter';
// all routes
import cors from 'cors';
const app = express();
app.use(bodyParser.json());
app.use(cors());
//use all routes
app.use(bodyParser.urlencoded({ extended: false }));
const port = process.env.PORT || 8003;
app.get('*', (req, res) => res.status(200).send({
message: "Entrance"
}));
app.listen(port, () => {
console.log("Entrance done, We are running at port " + port);
});
export default app;
Expectations:
It should log "entrance done we are running on port 8003" for (npm run dev)
It should log "entrance done we are running on port 5000" for(heroku local web)
Actual:
throw new TypeError('Parameter "url" must be a string, not ' + typeof url);
You should add -r dotenv/config to your starting script to preload dotenv =>
"start": "export NODE_ENV=production && sequelize db:migrate && node -r dotenv/config ./build/index.js",
Check docs