changing port not working in vuejs project - node.js

I have made a sample app in vuejs and try to change the port number. However this seems not to work as I get connection refused on that particular port, like nothing is being served on that port.
So I made a vue.config.js file in the root of my vuejs project.
This config file looks like this:
const BundleTracker = require("webpack-bundle-tracker");
module.exports = {
outputDir: './dist/',
chainWebpack: config => {
config.optimization
.splitChunks(false)
config
.plugin('BundleTracker')
.use(BundleTracker, [{filename: '../frontend/webpack-stats.json'}])
config.resolve.alias
.set('__STATIC__', 'static')
config.devServer
.public('http://0.0.0.0:8080')
.host('0.0.0.0')
.port(8080)
.hotOnly(true)
.watchOptions({poll: 1000})
.https(false)
.headers({"Access-Control-Allow-Origin": ["\*"]})
}
};
When I do 'npm run serve', I get the following:
App running at:
- Local: http://localhost:21739/
- Network: http://0.0.0.0:8080/
Note that the development build is not optimized.
To create a production build, run npm run build.
The port at 21739 is working but the one at 8080 is not working?
Does anyone have any idea what I am doing wrong here, or did I forget something?

Found a somewhat hacky fix. In node_modules/#vue/cli-service/lib/commands/serve.js there is this line that defines the port it is like:
const port = await portfinder.getPortPromise()
I have changed it to
const port = args.port || process.env.PORT || projectDevServerOptions.port
Now everything loads well. Don't know why they choose that approach and if there is a better way to handle this i'd like to know.

Related

Basic express setup: not sending anything to local port

I created a frontend app and now trying to incorporate backend into it.
ON the same frontend app i added an index.js file in the root directory, and installed express and required it in index.js file.
Very basic setup as below:
const express = require('express')
const cors = require('cors')
const port = process.env.PORT || 3001
const app = express()
app.get('/', (req, res) => {
res.send({
greetings: 'hi'
})
})
app.listen(port, () => {console.log(`Server on port ${port}`)})
Server is successfully on port 3001 as per my terminal, however, on localhost:3001 I'm not seeing any json response I set up in app.get.
It says Cannot GET / instead. When i inspected in devtool(Network) it says 404.
This seems a very straightforward setup, but what could've gone wrong here?
i just figured why. I installed nodemon but my “start” script is “node index.js”. Should’ve used “nodemon index.js”
Working now with nodemon index.ks
Your code is fine, There are no errors, I tested it and it works as expected.
However few things to note, Keep Backend in Seperate folder/dirctory unless required.
Coming back to your question, There are many possiblity such as some modules are not installed properly
try running following command
//this will install if any library is currupt or not installed properly
npm i
if it doesn't work then try clearing cache
Also keep in mind, In nodeJS dev server does not automatically refresh changes, you need to restart server to see changes or you can use dev dependancy called Nodemon (this will auto restart server on saving changes)

Elastic Beanstalk Problem: Connection timing out when running my Node.js Express server

I'm trying to deploy my MERN app on Elastic Beanstalk, and I seem to be running into a final problem that I just cannot solve.
My app works fine when running my server locally (running node server), but when running on elastic beanstalk, the page never loads.
Upon inspection, the static elements are not being loaded, as seen in Dev Tools:
Image showing ERR_CONNECTION_TIMED_OUT in dev tools
I checked all the EB logs and did not find any errors or helpful messages.
I'm thinking the problem is with EB not being able to find my static files somehow. It should however, my build files are not ignored by git and are deployed to EB.
Here's some background about my project:
My backend and client code are in one project, with the following structure:
project
server.js
frontend
build
static
index.html
I run my app by building the react site, then running "node server" which runs great
Here is the relevent code from my server.js :
const port = process.env.PORT || 8081;
app.use(express.static(path.join(__dirname, 'frontend/build')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'frontend/build/index.html'));
});
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
The server is successfully sending logs that the server is running and that the database has established a connection. So it seems the server is fine, it's just that the front-end is the problem.
eb config file:
option_settings:
aws:elasticbeanstalk:container:nodejs:
NodeCommand: "npm start"
aws:elasticbeanstalk:application:environment:
PORT: 8081
NODE_ENV: production
aws:elasticbeanstalk:container:nodejs:staticfiles:
/static: /frontend/build/static
I'm at a loss on how to solve this. The EB was deployed through the CLI and I haven't messed with any settings. I'm letting EB know where my static files are, and I believe it would say not found, rather than timing out.
Any help would be appreciated
Solved.
The problem was with using Helmet in my express server. I had ommited the code, thinking it not relevant, but here is the top portion of server.js, with the last line being the relevant portion:
const AWS = require('aws-sdk');
const cors = require('cors');
const express = require('express');
const helmet = require('helmet');
const mongoose = require('mongoose');
const path = require('path');
let Download = require('./models/Download.js');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 8081;
app.use(helmet());
Not using helmet solves the issue.
To be honest, I'm not sure why this is the problem.
I assume that the problem is that helmet provides some security that my bare bones EB simply is not providing.
EDIT: Specifically, the problem is with CSP. Setting contentSecurityPolicy to false in Helmet is enough to fix the issue.

How to fix "Error: The server does not support SSL connections" when trying to access database in localhost?

I am following Heroku's node.js tutorial to provision a Postgres database.
After creating a simple table and connecting to localhost:5000/db, I get an error saying "Error: The server does not support SSL connections".
I've been searching for solutions for hours but can't seem to fix it. Your help will be greatly appreciated. Thank you!
Here I provide a workaround for the question, and not the title of this post. A better answer to the post overall would probably address configuring SSL for the local machine.
I arrived here trying to resolve the problem of finishing that Heroku tutorial mentioned in the question and setting up the Postgres database to work locally as well as remotely.
const pool = new Pool({
connectionString: process.env.DATABASE_URL || 'postgresql://postgres:<your admin password>#localhost:5432/<your db name>',
ssl: process.env.DATABASE_URL ? true : false
})
My idea is to use SSL on the app I deploy but dodge SSL altogether on the local machine. By simply skipping SSL config on the local machine I am able to concentrate my efforts on developing a working app that still uses Heroku's built in SSL.
I use the Heroku environment variables to detect their environment versus my own and I select values accordingly in the code sample above. For me this has worked both locally and remotely.
This is the new form Heroku is working today in 2021, they made small corrections in the connection.
const pool = (() => {
if (process.env.NODE_ENV !== 'production') {
return new Pool({
connectionString: process.env.DATABASE_URL,
ssl: false
});
} else {
return new Pool({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
});
} })();
They changed a bit, using this way you can keep local and heroku available.
I had the same issue for setting up my local environment after the tutorial. Sticking to the command heroku local to start my server fixed it for me. This command is detailed in the Run the app locally section of the tutorial.
In my case I added a Express server and a client side using React + Webpack. My package.json scripts for local development look like:
"dev": "run-p dev:*",
"dev:server": "heroku local -f Procfile.dev",
"dev:webpack": "webpack --watch --config webpack.dev.js --mode development",
run-p is just from npm-run-all to run all scripts starting with dev at the same time.
The server uses the heroku local command and a specific Procfile for local development (use -f flag to do this), where I start a server locally with nodemon to watch for changes (see the Procfile.dev below).
The webpack script builds and watches for changes on the client side with React.
Procfile.dev for local development:
web: nodemon index.js
Procfile for production:
web: node --optimize_for_size --max_old_space_size=920 --gc_interval=100 index.js
Then the same code for connecting to the DB from the Provision a database section works for me:
const { Pool } = require('pg');
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
});
I came here not looking for a localhost solution (I wanted to connect to my db which is online), however, this turned up as the first google result, so I'll add a solution for not localhost issues here:
Check out the .env file to duplicate the Environment variables you setup in your heroku environment; see here: https://devcenter.heroku.com/articles/heroku-local#set-up-your-local-environment-variables
const pool = new Pool({
connectionString: process.env.DATABASE_URL || 'postgresql://postgres:#localhost:5432/',
ssl: process.env.DATABASE_URL ? true : false
})
In your code, you add this snippet with the credentials and connection string details, here process.env.DATABASE_URL comes from environment file, if it is there as it will enable ssl mode, else in local without ssl it works. Make sure, you will mention env variable only for other than local. So on both environment it works.
This helped me, when I was using connectionUrl.
postgres://password:postgres#localhost:5432/database?sslmode=disable
You might have noticed I have added ?sslmode=disable at the end of
connection url.
For more information about sslmode check this out.
To fix this I had to edit the database.js file.
Path to file:
<path-to-your-strapi-project>/config/database.js
if you find something with ssl that is set to true set it to false. In my case, I used Mysql it looked like this:
ssl: env.bool('DATABASE_SSL', true)
Change it to:
ssl: env.bool('DATABASE_SSL', false)
Best solution that I found that worked only:
const client = new Client({
connectionString: productiondbLink || localdblink,
ssl: process.env.DATABASE_URL ? { rejectUnauthorized: false } : false
});
client.connect();

Cannot get correct static files after refreshing except index page

When I refresh page on index route (/) and login page (/login), it works fine.
However, my website gets error as I refresh on other routes, for example /user/123456.
Because no matter what the request is, the browser always gets HTML file.
Thus, both of the content in main.css and main.js are HTML, and the browser error.
I have already read the README of create-react-app.
Whether I use serve package ($serve -s build -p 80) or express, it will produce the strange bug.
Following is my server code:
//server.js
const express = require('express');
const path = require('path');
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
const PORT = process.env.PORT || 80;
app.listen(PORT, () => {
console.log(`Production Express server running at localhost:${PORT}`);
});
Edit: I have figured out where caused the problem.
I created a new project, and compared it to mine. The path of static files in the new project is absolute, but in my project is relative.
As a result, I delete "homepage": "." in the package.json.
//package.json
{ ....
dependencies:{....},
....,
- "homepage": "."
}
Everything works as expected now. How am I careless...
I have figured out where caused the problem.
I created a new project, and compared it to mine. The path of static files in the new project is absolute, but in my project is relative.
As a result, I delete "homepage": "." in the package.json.
//package.json
{ ....
dependencies:{....},
....,
- "homepage": "."
}
Everything works as expected now. How am I careless...
If your route /user/** is defined after app.get('/*', ... it might not match because /* gets all the requests and returns you index.html.
Try without the * or declare the other routes before.
First, I thought you misunderstood the server part. In your case, you use serve as your server. This is a static server provided by [serve]. If you want to use your own server.js, you should run node server.js or node server.
I also did the same things with you and have no this issue. The followings are what I did:
create-react-app my-app
npm run build
sudo serve -s build -p 80 (sudo for port under 1024)
And I got the results:
/user/321
I guessed you might forget to build the script. You can try the followings:
remove build/ folder
run npm run build again
Advise: If you want to focus on front-end, you can just use [serve]. It will be easy for you to focus on what you need.

Deploy React.js Starter Kit on Openshift

I'm trying to deploy the Starter Kit of React.js (available here : https://github.com/kriasoft/react-starter-kit) on Openshift. To do that, I modified some little things that I explain here.
First, the logs in Openshift tells me that the import keyword in the servers.js file is not recognized. I think Babel is not used by Openshift at this point.
A workaround for that is mentioned here : How do I modify the node startup command in Open Shift?
So I modified the server.js content (because Openshift run the node server.js command and not the babel-node tools/run start defined in the scripts.start property of package.json) with the recommended content and renamed my base server.js to app.js.
Now, the logs tells me that babel-core is not found so I modified the package.json file to put babel-core and babel-cli in dependencies instead of devDependencies and remove a DEV value of another property.
All the times, when I push my code on Openshift (code of the src folder), the compilation failed at a random time (when dependencies are installed) and it take a long long time. However, when I reboot the cartridge I can see logs I explained.
My current situation is that things are looking better but the problem is the disk space : not enough. That's surprising me because the cartridge can host 1GB and on my local machine all files with dependencies take ~148MB. I tried to delete and recreate the cartridge : the same thing appears.
Does anybody know what can be wrong here ? The fact that the cardridge exceed 1GB is weird...
Thank you all.
Here's the solution... I hope it will save hours for some people !
Set the "production" mode to the cartridge app (so that in don't download so many inodes) :
rhc set-env NODE_ENV=production --app appname
Don't forget to modify config.js :
export const port = process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || 3000;
export const host = process.env.OPENSHIFT_NODEJS_IP || 'localhost';
export const databaseUrl = 'sqlite:' + process.env.OPENSHIFT_DATA_DIR + 'database.sqlite';
Modify app.js (include the host):
import { port, host, auth, analytics } from './config';
//...
models.sync().catch(err => console.error(err.stack)).then(() => {
app.listen(port, host, () => {
console.log(`The server is running at http://${host}:${port}/`);
});

Resources