so, it just says 'cannot GET /' everytime i try to view my app
here is the code
server.js
//Import requiered packages
const express = require('express');
const {Client} = require('pg');
//Create the conection to the postgres server
const client = new Client({
connectionString: process.env.DATABASE_URL
});
client.connect();
//Create the express app
const bodyParser = require('body-parser');
const app = express();
// parse application/json
app.use(bodyParser.json());
//Handle a post request at /query
app.post('/query', (req, res) => {
res.setHeader('Content-Type', 'application/json');
console.log("Receiving request");
if(req.body.query) {
console.log(req.body.query);
client.query(req.body.query, (err, r) => {
if (err) throw err;
rows = [];
for(let row of r.rows){
rows.push(row);
}
response = JSON.stringify(rows);
console.log(response);
res.end(response);
});
}
});
const port = process.env.PORT || 8080
//Start listening
const server = app.listen(port, function () {
console.log("App listening at ${host}")
});
package.json
{
"name": "haha",
"description": "joseph = obesity > lawa",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "4.x.x",
"pg": "7.x.x",
"body-parser": "1.18.x"
}
}
I literally have no clue what's wrong and theres almost no erroirs in the CLI.
The errors in the CLI are basically irrelevant to this, as even if tehre are no errors im still presented with the 'cannot GET /' message
please help me :(
Related
I am trying to test different endpoints with a express server.
here is my app.js
const express = require('express');
const app = express();
const cors = require('cors');
const port = 5000;
const dogFunctions = require('./Models/Dog')
const { Pool, Client } = require('pg')
app.use(cors());
app.use(express.json());
const dogRoutes = require('./routes/dogs');
app.use('/dogs', dogRoutes);
app.get('/', (req, res) => res.send('Hello, world!'))
module.exports = app;
this is my config file for testing
const { Pool } = require('pg');
const fs = require('fs');
const request = require('supertest');
const apiServer = require('../../app');
const reset = fs.readFileSync(__dirname + '/reset.sql').toString();
// enable resetting of db between tests
const resetTestDB = () => {
return new Promise (async (res, rej) => {
try {
const db = new Pool();
await db.query(reset)
res('Test DB reset')
} catch (err) {
rej('Could not reset TestDB')
}
})
}
// make these things available to test suites
global.request = request
global.app = apiServer
global.resetTestDB = resetTestDB
here is one of the test files of mine:
describe('dogs endpoints', () => {
let api;
beforeEach(async () => {
await resetTestDB()
})
beforeAll(async () => {
api = app.listen(5000, () => console.log('Test server running on port 5000'))
});
})
here is what my package.json looks like
"scripts": {
"test": "jest --watchAll",
},
"jest": {
"testEnvironment": "node",
"coveragePathIgnorePatterns": [
"/node_modules/"
]
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"pg": "^8.8.0"
},
"devDependencies": {
"jest": "^29.3.0",
"supertest": "^6.3.1"
}
}
What have i done wrong here?
I think its something simple.. but cant figure it out.
I am using global of jest to attach my express to be able available as app in my test files as a global variable.
I have also set my test env to be node to be able to test for node applications.
Is there anything i missed?
so, after trying a few times, it is clear that I am doing something wrong but I do not realize what. My steps are:
rm -rf .next/ && npm run build
upload .next, package.json,next.config.js and server.js to cPanel file manager
create node JS app from cPanel with 14.18.3 version. (on my local node -v show me 14.18.1, but on cPanel I don't have this version)
run npm install with success
then i'm geting 503 service unavailable.
server.js
// server.js
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const hostname = 'localhost';
const port = process.env.PORT || 3000;
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer(async (req, res) => {
try {
// Be sure to pass `true` as the second argument to `url.parse`.
// This tells it to parse the query portion of the URL.
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
if (pathname === '/a') {
await app.render(req, res, '/a', query);
} else if (pathname === '/b') {
await app.render(req, res, '/b', query);
} else {
await handle(req, res, parsedUrl);
}
} catch (err) {
console.error('Error occurred handling', req.url, err);
res.statusCode = 500;
res.end('internal server error');
}
}).listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://${hostname}:${port}`);
});
});
package.json scripts
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
},
next.config.json
/** #type {import('next').NextConfig} */
const nextConfig = {
basePath: '/apps/nextjs-cpanel',
trailingSlash: true,
reactStrictMode: true,
sassOptions: {
additionalData: `#import "./styles/variables.scss"; #import "./styles/mixins.scss";`,
}
};
module.exports = nextConfig;
on cPanel application root is apps/nextjs-cpanel, application url is my-domain/apps/nextjs-cpanel and application startup file server.js
Bizarre situation going on here with my websocket. It's giving me the error
Error during WebSocket handshake: Unexpected response code: 200
Which for the life of me I cannot figure out why.
I've set up a very similar server with the exact same code with the exact same servers & settings. The only difference is one server has a .com TLD while the other has a .sg TLD.
I've reduced it down to the simplest form, which is the below and the error is still happening. It's on the api side for sure and not the frontend as the frontend can connect to the .com TLD.
Below is all the code that I believe is related to the problem. If you think there might be other areas please ask and I will post other areas. It's hosted on AWS Elastic Beanstalk. I've also set the SSL cert to domain.com & *.domain.com
Does anybody know why this might be happening?
The bizarre thing to me is I literally set up a server with these exact settings and it's working perfectly fine.
server.js (start point in package.json)
'use strict';
(async function() {
// Server Setup
const WSServer = require('ws').Server;
const app = await require('./app.js');
const server = require('http').createServer(app);
const port = 3075;
// Create web socket server on top of a regular http server
const wss = new WSServer({
server: server
});
// Also mount the app here
// server.on('request', app);
let sendMessage = {
"connected":"connected to web socket",
}
wss.on('connection', function connection(ws) {
ws.send(JSON.stringify(sendMessage));
ws.on('message', async function incoming(message) {
let interval = setInterval(async () => {
console.log("ping");
ws.send(message);
}, 500);
});
ws.on('close', function close() {
console.log('/socket connection Closed');
});
});
server.listen(process.env.PORT || port, function() {
console.log(`AppName https/wss is listening on port ${process.env.PORT || port}`);
});
})();
app.js (removed much of the code that is irrelevant to this question)
module.exports = (async function() {
const {Config,Environments} = await require("./common/config");
const packageJson = require('./package.json');
// Handler
const AuthFunc = await require("./funcs/user/auth");
const BillingFunc = await require("./funcs/billing/billing");
const ObjectUtil = require("./utils/object");
const AccountStatusEnum = require("./enums/account-status").accountStatusEnum;
const sleep = require('util').promisify(setTimeout);
const {t} = require('./translations/i18n').i18n;
const {availableLanguages} = require('./translations/all');
// Simulate real API calls
const delayResponse = 250;// milliseconds
// ==============================================
// Base setup
// ==============================================
process.env.TZ = "Etc/GMT"
const express = require('express');
const app = express();
var expressWs = require('express-ws')(app);
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(require('express-useragent').express());
// Cors
app.use(async function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, auth-id, auth-token, x-csrf-token, _csrf");
res.header('Access-Control-Allow-Methods', 'PATCH, POST, GET, DELETE, OPTIONS');
next();
});
// ==============================================
// Auth
// ==============================================
const normRoute = (req, res, next) => {
req.body = (req.body != undefined && req.body != null) ? ObjectUtil.toCamelCaseKeys(req.body) : req.body;
response(req,res,next(req));
}
// Does not need to be logged in but passes user info if logged in
const passRoute = async (req, res, next) => {
authRoute(req, res, next, AccountStatusEnum.any, true);
}
const authRoute = async (req, res, next, minimumStatus, passRoute) => {
req.body = (req.body != undefined && req.body != null) ? ObjectUtil.toCamelCaseKeys(req.body) : req.body;
let authId = (req.headers['auth-id'] !== undefined) ? req.headers['auth-id'] :"";
let authToken = (req.headers['auth-token'] !== undefined) ? req.headers['auth-token'] : "";
let r = await AuthFunc.authUser(
req,
req.ip,
req.useragent,
authId,
authToken,
minimumStatus,
);
if(r.err.code){
if(r.err.authError && passRoute){
response(req,res,next(req,null));
return false;
}else{
response(req,res,r);
return false;
}
}
let user = r.res.user;
r = await BillingFunc.updateSubStatus(req,user);
if(r.err.code){ response(req,res,r); return false; }
if(r.res.userStatus !== undefined){
user.status = r.res.userStatus;
}
response(req,res,next(req,user));
}
// ===============================================================
// Routes
// ===============================================================
app.get('/', function(req, res) {
res.send(
'<html>'+
'<head></head>'+
'<body>'+
'API is running <br>'+
'App: '+Config.FrontEnd.AppName+'<br>'+
'Env: '+Config.Env+'<br>'+
'Version: '+packageJson.version+'<br>'+
'</body>'+
'</html>'
);
});
// ==============================================
// Response type
// ==============================================
const response = async (req,res,obj) => {
await obj;
Promise.resolve(obj).then(function(val) {
if(delayResponse >= 1 && (Config.Env === Environments.Local)){
setTimeout(function(){
resume(req,res,val);
}, delayResponse);
return true;
}
resume(req,res,val);
});
}
const resume = (req,res,obj) => {
obj = (obj === undefined) ? {} : obj;
var status = (obj.status !== undefined) ? obj.status : 200;
// Let status override settings
if(obj.status === undefined){
if((obj.err.code)){
status = 400;
}else if(obj.res === undefined || ObjectUtil.isEmpty(obj.res)){
// status = 204;
}
}
let json = {};
json.err = obj.err;
json.res = obj.res;
json = ObjectUtil.toCamelCaseKeys(json);
res.status(status).json(json);
}
// ==============================================
// Return the app
// ==============================================
return app;
})();
package.json
{
"name": "name-api",
"version": "1.17.0",
"description": "name-api",
"main": "server.js",
"dependencies": {
"axios": "^0.21.1",
"cookie-parser": "^1.4.4",
"express": "^4.17.1",
"express-session": "^1.17.1",
"express-useragent": "^1.0.13",
"express-ws": "^4.0.0",
"googleapis": "^50.0.0",
"mocha": "^8.0.1",
"mysql": "github:mysqljs/mysql",
"nodemailer": "^6.4.6",
"query-string": "^6.12.1",
"stripe": "^8.60.0",
"ws": "^7.4.3"
},
"devDependencies": {},
"scripts": {
"test": "mocha",
"start": "node server.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/..."
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/..."
},
"homepage": "https://github.com/..."
}
Problem solved.
It was a load balancer issue. Apparently this doesn't work well with Classic Load Balancer. I believe it's due to the way it's requested.
Changing over to a Application Load balancer fixed the issue for me.
Project works as intended locally. To run locally, I currently run the command npm run start in both the project root and the client root concurrently.
I am working to create a simple application using Express and Create React App. Despite a successful build and no errors in my Heroku logs, my deploy shows a blank page that says "Not Found" and has a 404 error in the chrome console.
File directory:
client
> src
-> components
-> app.js
> package.json
routes
> tweets.js
index.js
package.json
Root package.json:
{
"name": "newStock",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"npm": "6.x",
"node": "12.x"
},
"scripts": {
"start": "node index.js",
"heroku-postbuild": "cd client && npm install && npm run build",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"password-generator": "^2.2.3",
"socket.io": "^2.3.0",
"socket.io-client": "^2.3.0",
"twitter": "^1.7.1"
}
}
Root index.js:
const express = require("express");
const http = require("http");
const socketio = require("socket.io");
const path = require("path");
const bodyParser = require("body-parser");
const app = express();
require("dotenv").config({ path: "./.env" });
require("./routes/tweets.js")(app, io);
const server = http.createServer(app);
const io = socketio(server);
//middleware
app.use(bodyParser.json());
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 || 3001;
console.log(`Password generator listening on ${port}`);
server.listen(port, () => {
console.log("server is up");
});
Root routes/tweets.js:
const Twitter = require("twitter");
module.exports = (app, io) => {
let twitter = new Twitter({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});
let socketConnection;
let twitterStream;
app.locals.searchTerm = "cake"; //Default search term for twitter stream.
app.locals.showRetweets = false; //Default
/**
* Resumes twitter stream.
*/
const stream = () => {
console.log("Resuming for " + app.locals.searchTerm);
twitter.stream(
"statuses/filter",
{ track: app.locals.searchTerm },
stream => {
stream.on("data", tweet => {
sendMessage(tweet);
});
stream.on("error", error => {
console.log(error);
});
twitterStream = stream;
}
);
};
/**
* Sets search term for twitter stream.
*/
app.post("/setSearchTerm", (req, res) => {
let term = req.body.term;
app.locals.searchTerm = term;
twitterStream.destroy();
stream();
console.log(req.body.term);
});
/**
* Pauses the twitter stream.
*/
app.post("/pause", (req, res) => {
console.log("Pause");
console.log(req.body.term);
twitterStream.destroy();
});
/**
* Resumes the twitter stream.
*/
app.post("/resume", (req, res) => {
console.log(req.body.term);
console.log("Resume");
stream();
});
//Establishes socket connection.
io.on("connection", socket => {
socketConnection = socket;
stream();
socket.on("connection", () => console.log("Client connected"));
socket.on("disconnect", () => console.log("Client disconnected"));
});
/**
* Emits data from stream.
* #param {String} msg
*/
const sendMessage = msg => {
if (msg.text.includes("RT")) {
return;
}
socketConnection.emit("tweets", msg);
};
};
All I needed to do was reset the git cache of my client directory as it wasn't even being added to git because of this. I only noticed when I uploaded the repo to GitHub to save it for another day.
wow.
enter image description here
I am doing all this on codeanywhere
That should work. Unless..
Make sure you npm install express
Since your file is named app.js make sure in your package.json file it reads something like this.
Make sure main says app.js not index.js or server.js
{
"name": "stack-test",
"version": "1.0.0",
"main": "app.js",
"license": "MIT",
"dependencies": {
"express": "^4.16.2"
}
}
This will give you an err if something breaks.
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
app.get('/', function(req, res) {
res.send("Hi there");
})
app.listen(port, (err) => {
if (err) {
console.log(`Error: ${err}`);
} else {
console.log(`App running on port ${port}`);
}
});