Why express api doesn't GET this folder? - javascript

I have a js script for a server is required to GET files from folder called "public". But when I go to localhost it says Cannot GET / .The script is:
const express = require('express');
const app = express();
app.use('/', express.static('/public'));
app.listen(3000);
I am really new to js, express api, and web dev in general so could anybody help me?

I can't add a comment since I don't have the rep, but judging by your other comments you want to change the /public to ./public

Related

Using dotenv for API keys in multiple JS files

I am new to web programming but not programming in general. I use node.js to create a website and am using dotenv to hide API info form github and am having some trouble understanding something.
My .env file is in the root directory and contains:
GOOGLE_CALENDAR_API_KEY=key_value
I use an app.js file to set up and run my server and send the index.html file.
//jshint esversion:6
const https = require('https');
const bodyParser = require("body-parser");
const express = require("express");
require("dotenv").config();
const app = express();
app.use(express.static("public"));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
app.listen(5000, function(req, res) {
console.log("Listening on port 5000.");
});
Then I have another script file I use named "custom.js" to run the bulk of my webapp. Inside, I try to use process.env to get the API key.
window.onload = function()
{
const googleAPIkey = process.env.GOOGLE_CALEDAR_API_KEY;
.
.
.
but I get an error "Uncaught ReferenceError: process is not defined"
I have also tried moving the require("dotenv").config() line to the custom.js file and that fails. There is something I am doing wrong with trying to access information from one file into another, but I don't understand what.
Any help would be appreciated!
From what's i understood you trying to access the process variable of node.js app from the client browser and it is not possible. The process variable is only accessible in the scope of the node.js application and not in the browser where you run your client.
you have to add require("dotenv").config(); on second script file also
It looks like you are trying to access the Process variable on the client-side / frontend. You cannot access those variables from a client browser or machine

Correct NodeJS server for Vue.js application

I'm using Vue.js and the vue-router and would like to server the static files via Node.JS.
So I've create server.js with the following code:
// server.js
var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');
app = express();
app.use(serveStatic(__dirname + "/dist"));
var port = process.env.PORT || 5000;
app.listen(port);
console.log('server started '+ port);
It seems to work, but only when I click around.
If I visit ex. my-url.com/some-path/another-path it fails.
Am I missing something?
Ex. I'm getting:
Cannot GET /cars with I type www.my-domain.com/cars into the address bar in the browser, but visiting www.my-domain.com and clicking on cars does work.
You need to setup your server to redirect users to the appropriate server location. Please read the Vue Router - HTML5 History Mode docs.
When using history mode, the URL will look "normal," e.g.
http://oursite.com/user/id. Beautiful!
Here comes a problem, though: Since our app is a single page client
side app, without a proper server configuration, the users will get a
404 error if they access http://oursite.com/user/id directly in
their browser. Now that's ugly.
Not to worry: To fix the issue, all you need to do is add a simple
catch-all fallback route to your server. If the URL doesn't match any
static assets, it should serve the same index.html page that your
app lives in. Beautiful, again!
The main thing that you need to do is have all routes lead to the root route. Alternatively, since you are using Express, you can leverage the connect-history-api-fallback which the Vue Router docs recommend.

Static site with express using a public fonder

I think this is probably just a misunderstanding of how to do this on my part but its bugging me and I haven't found anything to answer the problem.
I have a static site where my file structure is
--node_modules
--index.html
--server.js
--app.js
my server.js is simple its just
var express = require("express");
var cors = require("cors");
var app = express();
app.use(cors());
app.use(express.static(__dirname + '/'));
app.get('/question', function(req, res){
res.send(req.body);
});
// Start the server on port 3000
app.listen(process.env.PORT || 3000);
// Print out a nice message so you know that the server started
console.log('Server running on port 3000');
and my bootstrap and angular WORKS...your probably wondering what the problem is....
So I have a 2nd site and I building and thought I would organize my stuff a little better. My file structure is
--node_modules
--public
|---index.html
|---app.js
--server.js
The only difference in my server.js is
app.use(express.static(__dirname + '/public'));
my bootstrap and angular is referenced in index.html like
<script src="../node_modules/angular/angular.js"></script>
<script src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
This DOESN'T work!...now I know I could just do it the first way or use a CND but I was wondering if anyone could educate me as to why and what I am doing wrong.
All help and education is greatly appreciated.
Angular and Bootstrap probably shouldn't be in node_modules unless you are using Browserify. Express won't serve any static files that aren't under the express.static root, so you can't use ../ relative paths if they go higher than public/.
That is, you need to move everything that you want to be public somewhere under public/ including index.html and the JavaScript libraries you will use.

node.js /socket.io/socket.io.js not found

i keep on getting the error
/socket.io/socket.io.js 404 (Not Found)
Uncaught ReferenceError: io is not defined
my code is
var express = require('express'), http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);
and
<script src="/socket.io/socket.io.js"></script>
what is the problem ???
any help is welcome!
Copying socket.io.js to a public folder (something as resources/js/socket.io.js) is not the proper way to do it.
If Socket.io server listens properly to your HTTP server, it will automatically serve the client file to via http://localhost:<port>/socket.io/socket.io.js, you don't need to find it or copy in a publicly accessible folder as resources/js/socket.io.js & serve it manually.
Code sample Express 3.x -
Express 3 requires that you instantiate a http.Server to attach socket.io to first
var express = require('express')
, http = require('http');
//make sure you keep this order
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
//...
server.listen(8000);
Happy Coding :)
How to find socket.io.js for client side
install socket.io
npm install socket.io
find socket.io client
find ./ | grep client | grep socket.io.js
result:
./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js
copy socket.io.js to your resources:
cp ./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js /home/proyects/example/resources/js/
in your html:
<script type="text/javascript" src="resources/js/socket.io.js"></script>
It seems that this question may have never been answered (although it may be too late for the OP, I'll answer it for anyone who comes across it in the future and needs to solve the problem).
Instead of doing npm install socket.io you have to do npm install socket.io --save so the socket.io module gets installed in your web development folder (run this command at the base location/where your index.html or index.php is). This installs socket.io to the area in which the command is run, not globally, and, in addition, it automatically corrects/updates your package.json file so node.js knows that it is there.
Then change your source path from '/socket.io/socket.io.js' to 'http://' + location.hostname + ':3000/socket.io/socket.io.js'.
... "You might be wondering where the /socket.io/socket.io.js file
comes from, since we neither add it and nor does it exist on the filesystem. This is
part of the magic done by io.listen on the server. It creates a handler on the server
to serve the socket.io.js script file."
from the book Socket.IO Real-time Web
Application Development, page 56
You must just follow https://socket.io/get-started/chat/ and all will work.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(3000, function(){
console.log('listening on *:3000');
});
If you are following the socket.io tutorial https://socket.io/get-started/chat/, you should add this line as below.
app.use(express.static(path.join(__dirname, '/')))
This is because in the tutorial, Express will only catch the url
/ and send the file of index.html.
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html')
})
However, in the index.html, you have a script tag (<script src="/socket.io/socket.io.js"></script>) requests the resouce of socket.io-client, which is not routed in index.js (it can be found in console-network that the url is http://localhost:3000/socket.io/socket.io.js).
Please check the directory path mentioned in your code.By default it is res.sendFile(__dirname + '/index.html');
make sure you index.html in proper directory
Steps to debug
npm install socket.io --save in static files (index.html) for example, you may have installed it globally and when you look at the debugger, the file path is empty.
Change your script file and instantiate the socket explicitly adding your localhost that you have set up in your server file
<script src="http://localhost:5000/socket.io/socket.io.js"></script>
<script>
const socket = io.connect("localhost:5000");
$(() =>
Double check that the data is flowing by opening a new browser tab and pasting http://localhost:5000/socket.io/socket.io.js you should see the socket.io.js data
Double check that your server has been set-up correctly and if you get a CORs error npm install cors then add it to the server.js (or index.js whatever you have chosen to name your server file)
const cors = require("cors");
const http = require("http").Server(app);
const io = require("socket.io")(http);
Then use the Express middleware app.use() method to instantiate cors. Place the middleware this above your connection to your static root file
app.use(cors());
app.use(express.static(__dirname));
As a final check make sure your server is connected with the http.listen() method where you are assigning your port, the first arg is your port number, for example I have used 5000 here.
const server = http.listen(5000, () => {
console.log("your-app listening on port", server.address().port);
});
As your io.on() method is working, and your sockets data is connected client-side, add your io.emit() method with the callback logic you need and in the front-end JavaScript files use the socket.on() method again with the call back logic you require. Check that the data is flowing.
I have also edited a comment above as it was the most useful to me - but I had some additional steps to take to make the client-server connection work.
If you want to manually download "socket.io/socket.io.js" file and attaché to html (and not want to get from server runtime) you can use https://cdnjs.com/libraries/socket.io
like
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.min.js" integrity="sha512-eVL5Lb9al9FzgR63gDs1MxcDS2wFu3loYAgjIH0+Hg38tCS8Ag62dwKyH+wzDb+QauDpEZjXbMn11blw8cbTJQ==" crossorigin="anonymous"></script>
while this doesn't have anything to do with the OP, if you're running across this issue while maintaining someone else's code, you might find that the problem is caused by the coder setting io.set('resource', '/api/socket.io'); in the application script, in which case your HTML code would be <script>type="text/javascript" src="/api/socket.io/socket.io.js"></script>.
If this comes during development. Then one of the reasons could be you are running a client-side file(index.html). But what you should do is run your server(example at localhost:3000) and let the server handle that static file(index.html). In this way, the socket.io package will automatically make
<script src="/socket.io/socket.io.js"></script> available on the client side.
Illustration(FileName: index.js):
const path = require('path');
const express = require('express');
const socketio = require('socket.io');
const port = 3001 || process.env.PORT;
const app = express();
const server = http.createServer(app);
const io = socketio(server);
//MiddleWares
app.use(express.json());
app.use(
express.urlencoded({
extended: false,
})
);
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile('index.html');
});
io.on('connect', (socket) => {
console.log('New user joined');
}
server.listen(port, () => {
console.log(`App has been started at port ${port}`);
});
After this run your server file by the command
node index.js
Then open the localhost:${port}, Replace port with given in the index.js file and run it.
It solved my problem. Hope it solves yours too.

Directory-Dynamic Node.JS express server

I am new with the whole web-server side of Node.JS,
Unfortunately I cannot find how to make my express server serve dynamic web pages.
I understand routes, and how they work.
Here's my code
var express = require('express');
var app = express();
app.get('/', function (req, res){
res.send('Hello There From Express!\n');
});
app.listen('200');
This will only server the / directory, everything else will fail.
How would i set this up where it will serve a dynamic webpage range,
So like if the user wanted to type in http://example.com/billing.html,
it would redirect to the billing.html file.
I don't want to have to put in a routing line for each page, I would like to be able to just dynamically serve webpages..
Sorry if i'm not making any sense, i'm not the best at asking questions.
If you are wanting to just have express serve a folder of static HTML files without dealing with each one individually, you could define your app as:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/html')); //where /html is a subfolder of your app
app.listen('200');
with /html containing all of your static files.

Categories