'Cannot GET /' when debugging express app in vs code - node.js

I'm trying to get debugging working on VS Code. I have my simple app
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var morgan = require('morgan');
app.use(morgan('dev'))
app.use(express.static('client'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var lions = [];
app.get('/lions', function(req, res){
res.json(lions);
});
var port = 3001;
app.listen(port);
console.log('on port ' + port);
when I run my server from terminal I get normal output and everything works normally.
PS > node .\server\server.js
on port 3001
GET / 200 5.557 ms - 1013
GET /style.css 200 1.908 ms - 10107
GET /app.js 200 2.584 ms - 61761
GET /lions 200 2.785 ms - 2
I get served all my files and my app works.
as soon as I try to debug my app (F5), console output is
C:\Program Files\nodejs\node.exe --inspect-brk=15065 api-design-node\server\server.js
Debugger listening on ws://127.0.0.1:15065/9339408e-bf15-475f-8add-767309dc82f5
on port 3001
nothing else.
and when I point my browser to localhost:3001 I get
Cannot GET /

This appens just because you have no route in your express app matching GET /, try adding
app.get('/', (req, res) => res.end('hello'))
to your code (or try going to /lions in your browser).
Hope it helps.

This code helped me
const path = require('path');
app.use(express.static(path.join(__dirname, "client")));
path.join will create absolute path for static file.
Looks like VS code run in different environment

Related

How to deploy reactJS app with json-server

I have actually deployed my React-app in the following way:-
ran the command: npm run build
Already had db.json file with dummy data.
Context, when I run
json-server --watch db.json -p 3001 -d 2000
the entire react-app works on the localhost
installed json-server using npm
created a server.js file
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
const port = process.env.PORT || 3001;
server.use(middlewares);
server.use(router);
server.listen(port);
created the app on heroku and pushed it to heroku master
The website for some reason only works when I run node server.js on my local-machine and it is making requests to my localport.
if that command isn't running the react-app cannot do the axios request to the DB.
I don't know what went wrong.
I used the following tutorial for this: https://github.com/jesperorb/json-server-heroku
My suspicions are that in my code I have created a basUrl.js file in which
export const baseUrl = 'http://localhost:3001/';
How should I change this to fix my problem?
Thanks for your help.
You should link your react folder built with the server (server.js), to do that add:
const express = require('express');
const path = require('path');
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
'build' is your react app's folder created after npm run build into your react app folder.
You have to install path and express modules if not.
And, You should get your json-server database in 'get' function, to use it with a specific url like: /db, just like this:
app.use('/db', middlewares, router);
But you should put /db before /* to not to open database with url /.
So, the result (server.js) will be:
const jsonServer = require('json-server');
const app = jsonServer.create();
const path = require('path');
const express = require('express');
const middlewares = jsonServer.defaults();
const router = jsonServer.router('db.json');
const port = process.env.PORT || 3001;
app.use('/db', middlewares, router);
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
server.listen(port);
I have Heroku running on my JSON server too. You need to correct your API path to be your resource name, for example;
If your resource name in your API is 'blogs';
{
"blogs": [
{
"postTitle": "My First Blog",
then your api path will be;
https://xxxx.herokuapp.com/blogs
OR
export const baseUrl = 'https://xxxx.herokuapp.com/blogs';
You shouldn't need to specify a port, but if you do it will be port 4000, which Heroku uses.

Failing to fetch data | Only affects mobile | Express / Postgres / Vue

My Vue app runs perfectly on desktop, but on mobile, it fails to fetch data when the app loads, leaving the components rendering but with no data to display.
Link to the app
Link to the entire Github repository
I diagnosed the issue by running it through Google's Mobile-Friendly Test tool: here are the results.
My index.js looks like this:
const express = require("express");
const serveStatic = require("serve-static");
const bodyParser = require("body-parser");
const cors = require("cors");
const db = require("./queries");
const app = express();
app.use(serveStatic(__dirname + "/dist"));
app.use(cors());
app.use(bodyParser.json());
app.get("/sizemenudata", db.getSizeMenuData);
app.get("/lightlevelmenudata", db.getLightLevelMenuData);
app.get("/easeofcaremenudata", db.getEaseOfCareMenuData);
app.get("/petsafemenudata", db.getPetSafeMenuData);
app.get("/menuTitles", db.getMenuTitles);
app.use(express.static("dist"));
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Listening on ${port}`);
});
Things to note:
I'm fetching the data from a postgres database, here is my sql file.
I have a seperate queries.js file which I import into index.js.
Closing this because it was a simple error, the Heroku ENV vars weren't set.

Why is expressjs returning the error "Cannot GET /" in the browser from code below?

Using the code below with nodejs, expressjs, socket io and pug
the browser response is Cannot GET /
Have had same or similar response to get in other code
Have index.pug file in root and views (just in case)
Tried various permutations such as "/", "./", "/views", "/views" etc
const express = require('express')
const socket = require('socket.io')
const app = express();
app.set('view engine','pug')
app.get("./", function(req, res){
res.render("home");
})
const runServer = app.listen(8585, ()=> console.log('server is running at 1 27.0.0.1:8585'))
Server runs at localhost:8585 in terminal (GIT bash) OK
Expected result: "Home" page in browser
Actual result: the browser when "./" response is Cannot GET /
If using "/" (vs "./") then terminal and browser either crash or respond with blank
Have you got a route for GET / set?
router.route('/').get(function (req, res) {
res.send('app successfully running.')
})
If you are rendering 'home' then why do you have index.pug inside views. You should have home.pug inside views folder. I tried the below code and it worked.
Folder structure:
- server.js
- views/home.pug
Code -
const express = require('express');
const app = express();
app.set('view engine','pug')
app.get("/", function(req, res){
res.render("home");
})
const runServer = app.listen(8585, ()=> console.log('server is running at 1 27.0.0.1:8585'))

express.js how show image?

I have images in /public folder and I want to show them..simply like this: <img src="a.jpg">
My app.js code
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
server.listen(8080);
app.use('/public', express.static(__dirname + "/public"));
If I open it in localhost this error is still showing
NetworkError: 404 Not Found - http://localhost:8080/public/a.jpg"
in your case it is enough to write:
app.use(express.static('public'));
it will serve directly the public folder.
an image in this path /public/images/somePhoto.png would be shown like that: http://localhost:8080/images/somePhoto.png
source: https://expressjs.com/en/starter/static-files.html
You need to drop the /public/ bit from your URL to your image.
So it becomes just http://localhost:8080/a.jpg
handling static files in express
You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly.
For example, if you keep your assests in a folder called public, you can use
app.use(express.static('public')) as follows, my images are in public\images
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
save the code above to server.js
$ node server.js
Now open http://127.0.0.1:8081/images/logo.png in any browser and image will show up

understanding modules/routes in nodejs

I'm new in nodejs. I want to build a rest service with multiple, lets say, categories.
> app.js
var express = require('express')
, http = require('http')
, routes = require('./routes')
, path = require('path');
app = express();
app.use(app.router);
app.get('*',routes.index);
app.listen(3000);
console.log('Express app started on port 3000');
and
> routes/index.js
var sites = [
'sve',
'ice'
];
exports.index = function(req,res){
var url = req.url.split('/');
for (i in sites) {
app.get('/' + sites[i] + '/*',require('./' + sites[i]));
}
};
and
> routes/sve/index.js
module.exports = function(req, res){
console.log('sve')
res.end({category:'sve'});
};
and
> routes/sve/index.js
module.exports = function(req, res){
console.log('sve')
res.end({category:'sve'});
};
when I run "node app" I get "Express app started on port 3000" and the server is running but when I access "localhost:3000/sve/test" I have no response or "localhost:3000/ice/test" or even "localhost:3000/abc/test".
Not even in the console.
What am I doing wrong?
As mentioned in my comment, I think you are looking for a method of using sub-apps (like Rails Engines) do modularize your application. If this is the case, you should use app.use() to mount a sub-app.
There's a good video on it here.
One last thing of relevance that isn't mentioned in the video, you can mount sub-apps relative. For instance:
var subapplication = require('./lib/someapp');
app.use('/base', app.use(subapplication));
This will treat the routes in subapplication as being from the '/base' path. For instance, a route catching '/a' in subapplication, when mounted in this example, will match a request to '/base/a'.

Resources