I am running my Angular Project on npm start and expect it to listen simultaneously to port 3000 (that is suppose to listen automatically to anything that is in the api folder).
Anyway, it looks like it is trying to listen to the port, but it keeps catching an error for who knows what reason
Doing a node BLL.js directly to see if there is a JSON output works like a charm, but having the REST api work does not seem to work weirdly.
package.json
{
"name": "project-vas",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxyConfig.json",
"build": "ng build --env=prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
proxyConfig.json
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"changeOrigin": true
}
}
api/DBConnection.js
exports.config = function()
{
return config = {
user: 'username',
password: 'password',
server: 'localhost',
database: 'databaseName'
};
}
api/BLL.js
const express = require('express');
const path = require('path');
const sql = require('mssql');
const app = express();
const connection = require('./DBConnection');
let config = connection.config();
const port = process.env.PORT || 3000;
app.use(express.static(__dirname + '/dist/ProjectName/'));
app.get('/*', (require, res) => res.sendFile(path.join(__dirname)));
app.get('api/usertypes', function (req, res) {
sql.connect(config, function (err) {
if (err) { console.log(err); }
else {
var request = new sql.Request();
request.query('sp_GETUSERTYPES', function (err, recordset) {
if (err) {
console.log(err);
}
res.send(recordset);
});
}
});
});
environment.ts
export const environment = {
production: false,
api:"http://localhost:3000",
};
Just the expected Stored Procedure output in the shape of a JSON array.
But 'Error occured while trying to proxy to: localhost:4200/api/usertypes' keeps getting returned whenever I try to test it on Postman.
Related
Trying to make my first Vue application, simple game with MEVN stack. Working perfect interacting with backend on development environment, however when hosting it doesn't fetch the data from the server.
Anyone able to point out what I have incorrect with the below?
More info below:
File structure:
/root
|- config.js
|- server.js
|- package.json + package-lock.json
|- client/
|- vue.config.json
|- ... (rest of dist, src, node_modules, public etc.)
|- models/
|- Elf.js + HighScore.js
|- routes/
|- api/
|- elf.js + highScore.js
config.js
module.exports = {
hostUrl: process.env.HOST_URL,
mongoURI: process.env.MONGO_URI,
PORT: process.env.PORT || 3000,
};
server.js
const express = require("express");
const app = express();
const port = 3000;
const mongoose = require("mongoose");
const { PORT, mongoURI } = require("./config.js");
// routes
const Player = require("./routes/api/player");
const Elf = require("./routes/api/elf");
const HighScore = require("./routes/api/highScore");
// cors is a middleware that allows us to make requests from our frontend to our backend
const cors = require("cors");
// morgan is a middleware that logs all requests to the console
const morgan = require("morgan");
// body-parser is a middleware that allows us to access the body of a request
const bodyParser = require("body-parser");
const path = require("path");
app.use(cors());
// use tiny to log only the request method and the status code
app.use(morgan("tiny"));
app.use(bodyParser.json());
// chek if we are in production
if (process.env.NODE_ENV === "production") {
// check if we are in production mode
app.use(express.static("client/dist"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "dist", "index.html"));
});
}
// test if server is running and connected to mongoDB
app.get("/", (req, res) => {
res.send("Hello World!");
});
// app.get("/", (req, res) => {
// res.send("Hello World!");
// });
// use routes
app.use("/api/", Player);
app.use("/api/", Elf);
app.use("/api/", HighScore);
mongoose
.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useUnifiedTopology: true,
})
.then(() => console.log("MongoDB connected..."))
.then(() => {
// log uri to console
console.log(`MongoDB connected to ${mongoURI}`);
})
.catch((err) => console.log(err));
app.listen(PORT, () => {
console.log(`Example app listening at ${PORT}`);
});
package.json
{
"name": "week1",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"server": "nodemon server.js --ignore 'client/'",
"client": "npm run serve --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"start": "node server.js",
"build": "npm install --prefix client && npm run build --prefix client"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.1",
"bootstrap": "^5.2.3",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"mongoose": "^6.7.5",
"morgan": "^1.10.0",
"portal-vue": "^2.1.7"
},
"devDependencies": {
"concurrently": "^7.6.0",
"nodemon": "^2.0.20"
}
}
Running within my dev environment at root dir using 'npm run dev', the app works flawlessly send/ receive data from mongoDB during this time. This starts up http://localhost:8080/. Also tried install of 'npm install -g serve' and running 'serve -s dist', this starts up serving at localhost:36797 and working flawlessly too.
I have tried to setup on Vercel & Render, both giving me the same issue where I'm not getting much feedback and the data isn't being fetched. Anyone else has this issue before?
I created Next Js project. I deployed it to my CPanel. And I created server.js file on directory.
I called next module as require in server.js. But When I access to my website I catch an error.
internal/modules/cjs/loader.js:638
throw err;
^
Error: Cannot find module 'next';
This error message.
My server.js code
const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const port = !dev ? process.env.PORT : 3000;
// Create the Express-Next App
const app = next({ dev });
const handle = app.getRequestHandler();
app
.prepare()
.then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
handle(req, res, parsedUrl);
console.log("pathname", pathname);
}).listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
})
.catch((ex) => {
console.error(ex.stack);
process.exit(1);
});
My package json
{
"name": "projectName",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
},
"dependencies": {
"express": "^4.17.1",
"next": "10.0.6",
"react": "17.0.1",
"react-dom": "17.0.1"
}
}
What should i do?
Thank you.
Best regards
Add this in your package.json dependency section : "#next/env": "^12.0.7"
I've already had problems publishing a next application other than on vercel. To fix the error I had to create a docker in order to publish the application. In case someone doesn't answer with a more viable solution, I recommend looking into using a docker.
I have created my first FullStack JS app. REACT for the front port :3000, NODE for the Back port 3001 and postgresql for database. And is also the first time I use Heroku !
My app called philosophybooks my database postgres is livres with one table books on this table 13 rows, 13 books in my db it's just for exemple :
author, title, date_of_parution, cover cover is just a string I've a folder illustrations_books in my frontend part of my app in this folder I have all images of the cover book
With CLI on windows I have well push all my app with my database all is well on Heroku. In front I've run a build folder and I have copy this one in back part of my app.
When I start heroku local web all work perfectly on http:localhost:5000
but when I launch my app not locally I have a console error
GET https://philosophybooks.herokuapp.com/livres 503 (Service Unavailable)
in front part in package.json I've"proxy": "http://localhost:3001"
little part of index.js
...
app.use(express.static('build'))
...
//Entry point API
app.get('/', (req, res) => {
res.send('My app is well connected and endpoint is OK')
})
//READ ALL
app.get("/livres", (req, res) => {
pool.query('SELECT * FROM books ORDER BY id ASC', (err, results) => {
if (!err)
res.status(200).json(results.rows)
else
console.log(err)
})
})
...
...
const port = process.env.PORT || 3001
app.listen(port, () => {
console.log(`[Express] is running on port ${port}`)
})
Little part of Livres.jsx in front part
...
...
useEffect(() => {
const fetchData = async () => {
setIsError(false)
try {
const result = await axios('/livres') /* 'http://localhost:3001/livres' */
setData(result.data)
} catch (error) {
setIsError(true)
console.log(error)
}
}
fetchData()
}, [])
...
...
config.js
require('dotenv').config()
const { Pool } = require('pg')
/* const pool = new Pool({
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
database: process.env.DB_DATABASE,
}) */
const isProduction = process.env.NODE_ENV === 'production'
const connectionString = `postgresql://${process.env.DB_USER}:${process.env.DB_PASSWORD}#${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_DATABASE}`
const pool = new Pool({
connectionString: isProduction ? process.env.DATABASE_URL : connectionString,
ssl: isProduction,
})
module.exports = { pool }
I have also a Procfile file web: node index.js
package.json backend part
{
"name": "philosophybooks",
"version": "1.0.0",
"description": "bibliothéque philosophique",
"main": "index.js",
"engines": {
"node": "12.x",
"npm": "6.x"
},
"scripts": {
"start": "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"NODEJS",
"JAVASCRIPT",
"ES6"
],
"author": "LC",
"license": "ISC",
"dependencies": {
"compression": "^1.7.4",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"helmet": "^4.1.1",
"nodemon": "^2.0.4",
"path": "^0.12.7",
"pg": "^8.3.3"
}
}
Render heroku local web
Render in prodhttps://philosophybooks.herokuapp.com/
I have to make a mistake that I don’t see or forget something, can you help me? if you need to see something else tell me. Thank you in advance for your help
EDIT Octobre 18, 2020
My database on HEROKU and via CLI pg:psql
Bonjour Parad0xJ,
PROBLEM:
It wasn't working because you were assigning an ssl certificate that wasn't verified. If you look at the heroku error carefully you will notice this error.
Error: self signed certificate
'DEPTH_ZERO_SELF_SIGNED_CERT'
const pool = new Pool({
connectionString: isProduction ? process.env.DATABASE_URL : connectionString,
ssl: isProduction, <=========== unverified self signed certificate
})
SOLUTION
Get rid of the ssl property in your pool configuration. Heroku already provides you a ssl so all you have to do is determine whether you want to disable or require it. You can read more here
const pool = new Pool({
connectionString: isProduction ? process.env.DATABASE_URL : connectionString,
sslmode: isProduction ? "require" : "disable"
})
Also you need to add the * route to the bottom because when it is at the top no other routes can be access:
app.get('*', (req, res) => { //<=========== Should be at the bottom of all routes
res.sendFile(path.join(__dirname, "frontend/build/index.html"));
});
Here is all the configuration in this git repo :
https://github.com/l0609890/philosophybook/invitations
I'm running Nuxt in Universal Mode with Koa as API / Controller in the backend based on the Koa template. I'm deploying to Heroku. API works fine locally, but returns 404 in production. I think that the app is running as SPA when deployed as everything else works well.
Here's my server/index.js
const Koa = require('koa')
const consola = require('consola')
const Router = require('koa-router');
const { Nuxt, Builder } = require('nuxt')
const api = require('./api');
console.log('server works'); // ------> This line gets ignored by the Heroku console
const app = new Koa()
const router = new Router();
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = app.env !== 'production'
router.use('/api', api.routes(), api.allowedMethods());
app.use(router.routes());
async function start () {
// Instantiate nuxt.js
const nuxt = new Nuxt(config)
const {
host = process.env.HOST || '127.0.0.1',
port = process.env.PORT || 3000
} = nuxt.options.server
// Build in development
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
} else {
await nuxt.ready()
}
app.use((ctx) => {
ctx.status = 200
ctx.respond = false // Bypass Koa's built-in response handling
ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
nuxt.render(ctx.req, ctx.res)
})
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`, // ------> Neither this line appears in Heroku console
badge: true
})
}
start()
Procfile
web: nuxt start
Scripts from package.json
"scripts": {
"dev": "cross-env HOST=192.168.1.65 NODE_ENV=development nodemon server/index.js --watch server ",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production node server/index.js",
"generate": "nuxt generate",
"test": "ava",
"test:unit": "cross-env TEST=unit ava --config unit.config.js",
"test:e2e": "cross-env TEST=e2e ava --config e2e.config.js",
"heroku-postbuild": "nuxt build"
}
I think I'm getting nu(x)ts after reading all these deployment docs and not seeing the obvious.
Thanks.
I didn't live any problem, attaching my package.json, server/index.js file and Heroku environment settings. You can check herokuapp from here
package.json
{
"name": "testkoa",
"version": "1.0.0",
"description": "My first-class Nuxt.js project",
"author": "Ahmet Zeybek",
"private": true,
"scripts": {
"dev": "cross-env NODE_ENV=development nodemon server/index.js --watch server",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production node server/index.js",
"generate": "nuxt generate"
},
"dependencies": {
"#nuxtjs/axios": "^5.3.6",
"#nuxtjs/dotenv": "^1.4.0",
"#nuxtjs/pwa": "^3.0.0-0",
"cross-env": "^5.2.0",
"koa": "^2.6.2",
"koa-router": "^7.4.0",
"nuxt": "^2.0.0"
},
"devDependencies": {
"nodemon": "^1.18.9"
}
}
server/index.js
const Koa = require("koa");
const Router = require("koa-router");
const consola = require("consola");
const { Nuxt, Builder } = require("nuxt");
const app = new Koa();
// Import and Set Nuxt.js options
const config = require("../nuxt.config.js");
config.dev = app.env !== "production";
async function start() {
app.use(async function handleError(ctx, next) {
try {
await next();
} catch (err) {
ctx.status = err.statusCode || err.status || 500;
ctx.body = err;
}
});
const router = new Router({ prefix: "/api" });
router.get("/:name", async ctx => {
ctx.response.body = `Hello ${ctx.params.name}`;
});
// Instantiate nuxt.js
const nuxt = new Nuxt(config);
const {
host = process.env.HOST || "127.0.0.1",
port = process.env.PORT || 3000
} = nuxt.options.server;
// Build in development
if (config.dev) {
const builder = new Builder(nuxt);
await builder.build();
} else {
await nuxt.ready();
}
app.use(router.routes());
app.use(router.allowedMethods());
app.use(ctx => {
ctx.status = 200;
ctx.respond = false; // Bypass Koa's built-in response handling
ctx.req.ctx = ctx; // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
nuxt.render(ctx.req, ctx.res);
});
app.listen(port, host);
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
});
}
start();
Heroku Config Vars
HOST=0.0.0.0
NODE_ENV=production
NPM_CONFIG_PRODUCTION=false
You don't need Procfile to use your Nuxt app on Heroku with this
configuration, remove it from your project folder
I'm taking an online course on writing block-chain from scratch.
The course utilizes javascript and node.js.
I am very new to these technologies but followed the course so far to the T.
i'm pasting the relevant code - the app file (index):
const express = require('express');
const bodyParser = require('body-parser');
const Blockchain = require('../blockchain');
const P2pServer = require('./p2p-server');
const HTTP_PORT = process.env.HTTP_PORT || 3001;
const app = express();
const bc = new Blockchain();
const p2pServer = new P2pServer(bc);
app.use(bodyParser.json());
app.get('/blocks', (req, res) => {
res.json(bc.chain);
});
app.post('/mine', (req, res) => {
const block = bc.addBlock(req.body.data);
console.log(`New blovk added: ${block.toString()}`);
res.redirect('/blocks');
});
app.listen(HTTP_PORT, () => console.log(`Listening on port ${HTTP_PORT}`));
p2pServer.listen();
and the code from p2p-server.js:
const Websocket = require('ws');
const P2P_PORT = process.env.P2P_PORT || 5001;
const peers = process.env.PEERS ? process.env.PEERS.split(',') : [];
//HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001 npm run dev
class P2pServer {
constructor(blockchain) {
this.blockchain = blockchain;
this.sockets = [];
}
listen() {
const server = new Websocket.Server({ port: P2P_PORT });
server.on('connection', socket =>this.connectSocket(socket));
this.connectToPeers();
console.log(`listening to peer-to-peer connections on: ${P2P_PORT}`);
}
connectToPeers() {
peers.forEach(peer => {
const socket = new Websocket(peer);
socket.on('open', () => this.connectSocket(socket));
});
}
connectSocket(socket){
this.sockets.push(socket);
console.log('socket connected');
}
}
module.exports = P2pServer;
when I try to run the following in the command line:
HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001 npm run dev
I get the following:
'HTTP_PORT' is not recognized as an internal or external command, operable program or batch file.
for some reason the process.env isn't picking up the input and passing it on to the app. What is wrong here?
Thanks!
EDIT: I was asked to add the package.json:
{
"name": "sf-chain",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest --watchAll",
"dev-test": "nodemon dev-test",
"start": "node ./app",
"dev": "nodemon ./app"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^23.1.0",
"nodemon": "^1.17.5"
},
"dependencies": {
"body-parser": "^1.18.3",
"crypto-js": "^3.1.9-1",
"express": "^4.16.3",
"ws": "^5.2.0"
}
}
You are using:
$ HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001 npm run dev
It is showing an error, because the window powershell will not recognize this command..
Instead you should use:
set HTTP_PORT=3002 && set P2P_PORT=5002 && set PEERS=ws://localhost:5001 && npm run dev
I believe were doing the same course. I'm sure you've probably figured this out but I tried the same step in Git Bash instead of Powershell and it worked.