Repository- https://github.com/sapinder-pal/Rest-Countries-App-ReactJS-SASS
I'm trying to transform my React app to SSR system. Although it works on localhost but throws an application-error when deployed to Heroku. The build logs show success, but an Application error is thrown on visiting the url.
PLEASE see the EDIT 1 where I've stated the root error.
Application Logs-
2020-09-21T05:23:05.915898+00:00 app[web.1]: npm ERR! rest-countriers#1.0.0 start: `node server/index.js`
2020-09-21T05:23:05.916046+00:00 app[web.1]: npm ERR! Exit status 1
2020-09-21T05:23:05.916211+00:00 app[web.1]: npm ERR!
2020-09-21T05:23:05.916335+00:00 app[web.1]: npm ERR! Failed at the rest-countriers#1.0.0 start script.
2020-09-21T05:23:05.916489+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-09-21T05:23:06.005989+00:00 app[web.1]:
2020-09-21T05:23:06.006055+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-09-21T05:23:06.006056+00:00 app[web.1]: npm ERR! /app/.npm/_logs/2020-09-21T05_23_05_918Z-debug.log
2020-09-21T05:23:06.234287+00:00 heroku[web.1]: Process exited with status 1
2020-09-21T05:23:06.275353+00:00 heroku[web.1]: State changed from starting to crashed
server/index.js-
require('ignore-styles');
require('#babel/register')({
ignore: [/(node_module)/],
presets: ['#babel/preset-env', '#babel/preset-react'],
plugins: ['#babel/transform-runtime']
});
require('./server');
server/server.js-
import express from 'express';
import fs from 'fs';
import path from 'path';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import {StaticRouter} from 'react-router-dom';
import App from '../src/App';
const PORT = process.env.PORT || 8080;
const app = express();
app.use(express.static(path.resolve('./build')))
app.get('*', (req, res) => {
fs.readFile(path.resolve('./build/index.html'), 'utf-8', (err, data) => {
if (err) {
console.log(err);
return res.status(500).send('Some error happened');
}
const context = {};
const app = ReactDOMServer.renderToString(
<StaticRouter location={req.url} context={context}>
<App />
</StaticRouter>
)
return res.send(
data.replace(
'<div id="root"></div>',
`<div id="root">${app}</div>`
)
);
});
});
app.listen(PORT, () => {
console.log(`App launched on ${PORT}`);
});
EDIT 1-
Looks like I've found the root error but don't quite know the reason-
/**** app.get() WORKS ONLY IF I DON'T SERVER THE 'BUILD' FOLDER. ****/
app.use(express.static(path.resolve('./build')));
/**** This function doesn't log anything if the *build* folder is served.
I got assured when I visited **Network** tab in devtools where I saw that
the *initial preview* for html file is blank, which means the file is not
rendered server-side ****/
app.get('*', (req, res) => {
console.log('got request');
....
}
I have index.html, index.css and index.bundle.js in the build folder.
You need to add heroku-postbuild command in your package.json
Your command would be something similar to
scripts:{
...
"build": ***,
"heroku-postbuild": "npm install && npm run build",
}
this will run and install your dependencies and will run the build command.
Try removing 'return' keyword
res.send(
data.replace(
<div id="root"></div>',
<div id="root">${app}</div>`
)
)
port should be
process.env.PORT || 3000
That's it. It should probably work now.
SOLVED!!!
There were two issues with the code-
The first one being that the app.get() method doesn't run was solved by moving app.use() statement below the former one.
However, I still don't quite understand the reason for this, because I think a middleware would still run before the callback function in the route method. If you know what's happening here, please let me know through comments!
The second issue, which made the start script fail, was because I was using #babel/core as a dev-dependency. So I re-installed it as a dependency only, and that fixed the error.
I'll still appreciate if anyone could explain the first point to me!
Related
I'm trying to make unit testing by jasmine but jasmine can't find the spec as the following error
and I don't know why I get such an error even though I just try running a very simple suite which always returns true !!!!
any advice would be appreciated
No specs found
Finished in 0.005 seconds
Incomplete: No specs found
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! img_process#1.0.0 jasmine: `jasmine`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the img_process#1.0.0 jasmine 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:my path
npm ERR! Test failed. See above for more details.
this is jasmine.json file
{
"spec_dir": "dist",
"spec_files": [
"**/*[sS]pec.?(m)js"
],
"helpers": [
"helpers/**/*.?(m)js"
],
"env": {
"stopSpecOnExpectationFailure": false,
"random": false
}
}
note: the spec.js files located successfully in dist directory after ts build
this is my index.ts file
import express, { Application, Request, Response } from 'express';
import dotenv from 'dotenv';
dotenv.config();
import routes from './routes/index';
const app: Application = express();
app.use(routes);
// app.use(supertest);
const port = process.env.PORT;
app.get('/', (req: Request, res: Response) => {
res.json({
message: 'Express + TypeScript Running '
});
});
app.listen(port, () => {
console.log(`⚡️[server]: Server is running at https://localhost:${port}`);
});
export default app;
this is the index.spec.ts file
import supertest from 'supertest';
import app from '../index';
const request = supertest(app);
describe('Test endpoint responses', () => {
it('gets the api endpoint', async (done) => {
const response = await request.get('/');
expect(response.status).toBe(200);
done();
}
)});
describe('placeholder', () => {
it('will always pass', async () => {
expect(true).toBe(true);
});
});
Console:
DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
server stared at port 7777
mongodb connection is successfull
events.js:200
throw er; // Unhandled 'error' event
^
ReferenceError: res is not defined
at D:\java script\React\hello\database\server.js:26:9
at D:\java script\React\hello\database\node_modules\mongoose\lib\model.js:4883:16
at D:\java script\React\hello\database\node_modules\mongoose\lib\model.js:4883:16
at D:\java script\React\hello\database\node_modules\mongoose\lib\helpers\promiseOrCallback.js:24:16
at D:\java script\React\hello\database\node_modules\mongoose\lib\model.js:4906:21
at D:\java script\React\hello\database\node_modules\mongoose\lib\query.js:4390:11
at D:\java script\React\hello\database\node_modules\kareem\index.js:135:16
at processTicksAndRejections (internal/process/task_queues.js:76:11)
Emitted 'error' event on Function instance at:
at D:\java script\React\hello\database\node_modules\mongoose\lib\model.js:4885:13
at D:\java scr
ipt\React\hello\database\node_modules\mongoose\lib\helpers\promiseOrCallback.js:24:16
[... lines matching original stack trace ...]
at processTicksAndRejections (internal/process/task_queues.js:76:11)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! Database#1.0.0 start: `node server.js "--port" "7777"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the Database#1.0.0 start 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! C:\Users\HP\AppData\Roaming\npm-cache\_logs\2020-06-11T07_56_43_613Z-debug.log
My code is: He is my server.js file. In which I an trying to post data into mongodb.
const express =require("express")
const app=express();
const path=require('path');
const bodyParser=require('body-parser');
const cors =require('cors');
app.use(cors());
app.use(bodyParser.json());
const structRoute=express.Router();
let Struct=require('./query.model');
const mongooes=require('mongoose');
mongooes.connect('mongodb://127.0.0.1:27017/query',{ useNewUrlParser: true });
const connection=mongooes.connection;
connection.once("open",function(){
console.log("mongodb connection is successfull");
})
structRoute.route('/').get(function(){
Struct.find(function(err,query){
if(err){
console.log("error");
}
else{
res.json(query);
}
});
});
structRoute.route('/:id').get(function(req,res){
let id=req.params.id;
Struct.findById(id,function(err,query){
res.json(query);
});
});
structRoute.route('/add').post(function(req,res){
let query=new Struct(req.body);
query.save()
.then(query=>{
res.status(200).json({'query':"added successfully"})
})
.catch(
err=>{res.status(400).send("adding failed");}
);
});
app.use('/Struct',structRoute);
enter code here
app.listen(7777,()=>{
console.log("server stared at port 7777")
})
You forget add req and res to this function.
structRoute.route("/").get((req, res) => {
Struct.find((err, query) => {
if (err) {
console.log("error");
} else {
res.json(query);
}
});
});
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.
I am running into the error
An error occurred in the application and your page could not be served.
when running 'heroku open' command. On heroku dashboard it says deployed successfully but then it will not run 'it is working' from the app.get line of code.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');
const register = require('./controllers/register');
const signin = require('./controllers/signin');
const profile = require('./controllers/profile');
const image = require('./controllers/image');
const db = knex({
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'benjohnson',
password : '',
database : 'smart-brain'
}
});
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.get('/', (req, res)=> { res.send('its working!') })
app.post('/signin', signin.handleSignin(db, bcrypt))
app.post('/register', (req, res) => { register.handleRegister(req, res, db, bcrypt) })
app.get('/profile/:id', (req, res) => { profile.handleProfileGet(req, res, db)})
app.put('/image', (req, res) => { image.handleImage(req, res, db)})
app.post('/imageurl', (req, res) => { image.handleApiCall(req, res)})
app.listen(process.env.PORT || 3000, ()=> {
console.log(`app is running on port ${process.env.PORT}`);
})
When running the server.js file within the heroku cli i receive the error, when running 'heroku logs --tail' i receive this error?
> node#1.0.0 start /Users/benjohnson/.Trash
> nodemon server.js
sh: nodemon: command not found
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! node#1.0.0 start: `nodemon server.js`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the node#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likel
y additional logging output above.
npm WARN Local package.json exists, but node_modules missing, di
d you mean to install?
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/benjohnson/.npm/_logs/2019-09-25T14_11_11_91
0Z-debug.log
The error is about nodemon.
Open the package.json, is at the same folder with server.js
Find:
"scripts": {
"start": " nodemon server.js",
},
And replace it with:
"scripts": {
"start": "node server.js",
"start:dev": "nodemon server.js"
},
Upload again in Heroku.
When you want to run the project locally, just run in your terminal npm start:dev and it will load server.js with nodemon.
I know I'm missing something here. I'm running node through babel and using koa2 on my server. Fairly new to this so not quite sure what I'm missing, as I've been referencing a lot of things online.
Versions: Node 6.4, babel-core 6.14.0, babel-polyfill": 6.13.0
Getting a fun error. Looks like a generator is not being produced somehow.
assert.js:89
throw new assert.AssertionError({
^
AssertionError: app.use() requires a generator function
at Application.app.use (/Users/administrator/Dropbox/Development/moonlite/moonlitewww/node_modules/koa/lib/application.js:106:5)
Here's what I'm running off of:
Package.json
"start:dev": "node -r babel-core/register index.js",
.Babelrc
{
"presets": ["es2015", "react", "stage-3"]
}
Index.js
require("babel-polyfill");
import nodeServer from "./web-server.js";
var config = {
prod: process.env.NODE_ENV === "production",
serverPort: process.env.PORT || 3000
};
nodeServer(config);
web-server.js
import Koa from 'koa';
import koaRouter from 'koa-router';
import send from 'koa-send';
import serve from 'koa-serve';
import logger from 'koa-logger';
const router = koaRouter();
const app = new Koa();
export default (config) => {
app.use(logger());
app.use(serve(__dirname + '/client/build'));
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(config.serverPort, () => {
console.log('Server running on port:' + config.serverPort);
});
};
What am I missing here?
Noob mistake on my part. I was merging the packages from another package.json file in, and somehow koa got reverted back to the 1.x branch. Was chasing a red haring thinking it was babel.
If you see a similar error double check your koa version, and upgrade to koa2 like so:
npm install koa#next --save
"NOW YOU KNOW, AND KNOWING IS HALF THE BATTLE..."