Problem when i run npm run dev in my node backend - node.js

I try to build API with node,and i have my frontend separated in folder called client,and this files(package.json,server.js is in my project root folder.
When i want to npm run dev,it gives me this error:
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! clothing-server#1.0.0 dev: `concurrently --kill-others-on-fail "npm server" "npm client"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the clothing-server#1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
Here is my server.js:
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
if (process.env.NODE_ENV !== 'production') require('dotenv').config();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
}
app.listen(port, error => {
if (error) throw error;
console.log(`Server running on ${port}`);
});
app.post('/payment', (req, res) => {
const body = {
source: req.body.token.id,
amount: req.body.amount,
currency: 'usd'
};
stripe.charges.create(body, (stripeErr, stripeRes) => {
if (stripeErr) {
res.status(500).send({ error: stripeErr });
} else {
res.status(200).send({ error: stripeRes });
}
});
});
and my package.json:
{
"name": "clothing-server",
"version": "1.0.0",
"engines": {
"node": "10.16.0",
"npm": "6.9.0"
},
"scripts": {
"client": "cd client && npm start",
"server": "nodemon server.js",
"build": "cd client && npm run build",
"dev": "concurrently --kill-others-on-fail \"npm server\" \"npm client\"",
"start": "node server.js",
"heroku-postbuild": "cd client && npm install && npm install --only=dev --no-shrinkwrap && npm run build"
},
"dependencies": {
"body-parser": "^1.19.0",
"compression": "1.7.4",
"cors": "2.8.5",
"dotenv": "8.2.0",
"express": "^4.17.1",
"stripe": "8.6.0"
},
"devDependencies": {
"concurrently": "^5.0.2"
}
}
I try to delete my lock file and node_modules and npm cache clean ,but they don't help

In your package.json file, It should be
"dev": "concurrently --kill-others-on-fail \"npm run server\" \"npm run client\""

Your npm run dev script calls npm server, which it tries to call nodemon server.js, but apparently the nodemon is not installed in your project. See your list of dependencies, and install nodemon, or remove it from server script.
Apparently it should work ;)

Related

Routing won't work once app is deployed to Heroku

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.

How to setup server file to read the right folder for NextJS app hosted on Heroku?

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.

Trying to run concurrently (npm ERR! code ELIFECYCLE npm ERR!)

I am trying to create a Full Stack Node & Vue application that takes data from an API. I am running into an issue where I am trying to run both the client and server concurrently but the code is running into an error. Please bear with me if I am structuring this question wrong as I am still fairly new to coding!
This is the following error log:
[0] Error occurred when executing command: npm run server
[0] Error: spawn cmd.exe ENOENT
[0] at Process.ChildProcess._handle.onexit (internal/child_process.js:267:19)
[0] at onErrorNT (internal/child_process.js:469:16)
[0] at processTicksAndRejections (internal/process/task_queues.js:84:21)
[1] Error occurred when executing command: npm run client
[1] Error: spawn cmd.exe ENOENT
[1] at Process.ChildProcess._handle.onexit (internal/child_process.js:267:19)
[1] at onErrorNT (internal/child_process.js:469:16)
[1] at processTicksAndRejections (internal/process/task_queues.js:84:21)
[1] npm run client exited with code -4058
[0] npm run server exited with code -4058
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! apex-tracker#1.0.0 dev: `concurrently "npm run server" "npm run client"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the apex-tracker#1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
From what I can tell the program is running fine up until it reaches the "dev" script in my package.json:
{
"name": "apex-tracker",
"version": "1.0.0",
"description": "Apex Legends user statistics tracker",
"main": "server.js",
"scripts": {
"start": "node server",
"server": "nodemon server",
"client": "npm run serve --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
"author": "Jared Mackay",
"license": "MIT",
"dependencies": {
"concurrently": "^5.0.1",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"morgan": "^1.9.1",
"node-fetch": "^2.6.0"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}
prior to the errors, the program ran fine when I ran the npm run server command, however upon installing the client folder and adding the client and dev script that's when I ran into my errors.
Here is my server.js that I am trying to run with the client:
const express = require('express');
const morgan = require('morgan');
const dotenv = require('dotenv');
//Load configuration file
dotenv.config({ path: './config.env' })
const app = express();
//Develper logging
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
//Profile routes
app.use('/api/v1/profile', require('./routes/profile'));
const port=process.env.PORT || 8000;
app.listen(port, () => {
console.log(`Server running on ${process.env.NODE_ENV} mode on port ${port}`);
});
I've tried clearing the npm cache, deleting and reinstalling node-modules as well as package-lock.json, but this created more issues rather than fixing them. I had to revert back to an old git commit and now I'm stuck.
I don't think this route .js file is an issue but here it is just in case profile.js:
const express = require('express');
const router = express.Router();
const fetch = require('node-fetch');
router.get('/:platform/:gamertag', async (req, res) => {
try {
const headers = {
'TRN-Api-Key': process.env.TRACKER_API_KEY
}
const { platform, gamertag } = req.params;
const response = await fetch(
`${process.env.TRACKER_API_URL}/profile/${platform}/${gamertag}`,
{
headers
}
);
const data = await response.json();
if(data.errors && data.errors.length > 0) {
return res.status(404).json({
message: 'Profile Not Found'
});
}
res.json(data);
} catch (err) {
console.error(err);
res.status(500).json({
message: 'Server Error'
});
}
});
module.exports = router;
Thank you in advance!
spawn cmd.exe ENOENT
Your program does not know where to find cmd.exe.

How to solve page not found error in heroku after deployment

I'm trying to upload an express/node.js app to heroku. The app is deployed succesfully but when I try to access the url I get error: Not Found.
When I run heroku logs --tail I get:
Error: ENOENT: no such file or directory, stat '/client/build/index.html'
so I think I'm doing something wrong with the directories and the statics folder
this is my server.js file:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const cors = require("cors");
const path = require("path");
const users = require("./routes/api/users");
const profile = require("./routes/api/profile");
const matches = require("./routes/api/matches");
const app = express();
//body-parser middleware
app.use(bodyParser.urlencoded({ extended: false, limit: "50mb" }));
app.use(bodyParser.json({ limit: "50mb" }));
//db config
const db = require("./config/keys").mongoURI;
//cors
app.use(cors());
//connect to mongoose
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
//Passport middleware
app.use(passport.initialize());
app.use("/images", express.static(path.join(__dirname + "/images")));
//Passport config
require("./config/passport")(passport);
//Use route
app.use("/api/users", users);
app.use("/api/profile", profile);
app.use("/api/matches", matches);
//Serve static assets if in production
if (process.env.NODE_ENV === "production") {
app.enable("trust proxy");
//Set static folder
app.use(express.static(path.join(__dirname, "/../client/build")));
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname + "/../client/build/index.html"));
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`server running on port ${port}`));
I also include an image of the folders "positions"
I solved this issue by defining build and install command in my package.json. Heroku would look for a build command for production in there.
"scripts": {
"build": "cd client && npm run build",
"install": "cd client && npm install",
"start": "node server",
"server": "nodemon server",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
I think it should be like this
app.use("/images", express.static(path.join(__dirname, "images")));
Edit: Actually your app is expecting to find a file at /../client/build/index.html but that file does not exist (which is what ENOENT error means). So you either need to create the expected directory structure or else configure your application such that it looks in the correct directory for index.html. That whats i understand now, i hope this would help you.
I also got similar error. For me the problem is I have wrong script for build in package.json file, So build is not creating at all.
Verify you have "heroku-postbuild" script as below in package.json file.
"scripts": {
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"clientinstall": "npm install --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},

How to build next.js production?

I try to get a production build in next.js to run it on my server but I can't build next.js production build when I try
npm run build
Does anyone know how to get a prod build in next.js working correctly I did everything in the next.js documentation but always get this error below. If I do a dev build it works just fine but trying prod build results in errors.
I did also next build many times and reinstalled all node_modules packages still having this error.
it always shows me in terminal
Error: Could not find a valid build in the '/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/.next' directory! Try building your app with 'next build' before starting the server.
at Server.readBuildId (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next-server.js:753:15)
at new Server (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next-server.js:80:25)
at module.exports (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next.js:6:10)
at Object.<anonymous> (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/next.config.js:6:13)
at Module._compile (internal/modules/cjs/loader.js:707:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:718:10)
at Module.load (internal/modules/cjs/loader.js:605:32)
at tryModuleLoad (internal/modules/cjs/loader.js:544:12)
at Function.Module._load (internal/modules/cjs/loader.js:536:3)
at Module.require (internal/modules/cjs/loader.js:643:17)
at require (internal/modules/cjs/helpers.js:22:18)
at loadConfig (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/config.js:47:28)
at _callee2$ (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/build/index.js:52:42)
at tryCatch (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:62:40)
at Generator.invoke [as _invoke] (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:288:22)
at Generator.prototype.(anonymous function) [as next] (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:114:21)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! hello-next#1.0.0 build: `next build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the hello-next#1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/kk/.npm/_logs/2018-12-10T19_58_00_588Z-debug.log
server.js
const express = require("express");
const next = require("next");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV === "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
next.config.js
const express = require("express");
const next = require("next");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV === "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get("/projects/:page", (req, res) => {
const page = req.params.page;
let file = "";
switch (page) {
case "example1":
file = "/projects/example1";
break;
case "example2":
file = "/projects/example2";
break;
}
return app.render(req, res, file, { page });
});
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
package.json
{
"name": "hello-next",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"dev": "node server.js",
"build": "next build",
"export": "next export"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#zeit/next-sass": "^1.0.1",
"express": "^4.16.4",
"next": "^7.0.2",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"redux": "^4.0.1",
"video-react": "^0.13.1"
}
}
If anyone has an idea would be so nice! I plan to run this next.js site using node on my AWS server. But to do this I need to get production build of react.js currently I can run just a development build.
Hope someone has an idea.
Thanks in advance!
next build followed by next start should be the right commands to prepare the build for production and run it.
Here's an example for package.json. if you want to export application to run as a static content, something like hosting it in s3 as a static website, you need to run next export
...
"scripts": {
"build": "next build",
"start": "next start",
"export": "next export"
}
...
Make sure you have the above scripts in your package.json then run the following in order
$ npm run build
$ npm run start
If you want to start application with specific port, you can specify -p port as argument for npm run command
npm run start -- -p 3232
If you want to incorporate this into a CI/CD pipeline, you need to have Dockerfile, here's a simple example
FROM node:alpine
#copy source
COPY . /app
# Install deps
RUN cd /app && npm install
# Build
RUN npm run build
ENTRYPOINT [ "npm", "run", "start" ]
Still need more explanation or help, don't hesitate to leave a comment and I will be more than happy to assist.
Seems your server.js config is not correct. Please try moving all you have from your next.config.js to server.js make sure the next.config.js file is empty then create a new npm run script:
"prod_start": "NODE_ENV=production node server.js"
Your package.json should then look like this:
{
"name": "hello-next",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"dev": "node server.js",
"build": "next build",
"prod_start": "NODE_ENV=production node server.js",
"export": "next export"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#zeit/next-sass": "^1.0.1",
"express": "^4.16.4",
"next": "^7.0.2",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"redux": "^4.0.1",
"video-react": "^0.13.1"
}
}
make sure to run: npm run build && npm run prod_start
Then you should have a production build of react running using next.js
Let me know if you got question.
You must launch next build at your root folder and not inside .next/
There are 3 ways todo it:-
way 1: use next build instead of npm run build
way 2: npm run build npm install -g serve serve -s build
more info: https://create-react-app.dev/docs/deployment/
way 3: after npm run build, Remove / from JS,CSS links from /static/index.html file. eg. replace these 2 lines
<script defer="defer" src="/static/js/main.aa87bc08.js"></script>
<link href="/static/css/main.073c9b0a.css" rel="stylesheet"/>
with these 2 lines
<script defer="defer" src="static/js/main.aa87bc08.js"></script>
<link href="static/css/main.073c9b0a.css" rel="stylesheet" />
now it even work on file:///D:/codes/ProjectName/build/index.html
tell me in the comments if none of the 3 ways work, I'll find, try & tell way 4, 5, etc.

Resources