How to fix error Cannot GET with Node.js / Express - javascript

I have a class Server :
Server.js
const express = require('express');
class Server {
constructor() {
this.app = express();
this.app.get('/', function(req, res) {
res.send('Hello World');
})
}
start() {
this.app.listen(8080, function() {
console.log('MPS application is listening on port 8080 !')
});
}
}
module.exports = Server;
I start my server in app.js :
const Server = require('./server/Server');
const express = require('express');
const server = new Server();
server.start();
server.app.use('/client', express.static(__dirname + '/client'));
My html code :
index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<title></title>
</head>
<body>
<div id="historique">
<button v-on:click="openHistorique">
Historique Proface
</button>
</div>
</body>
</html>
My index.js :
window.onload = function () {
var hist = new Vue({
el:'#historique',
methods: {
openHistorique: function() {
console.log("On clique");
document.location.href="../AffichageHistorique/index.php";
}
}
})
}
And the folder structure :
client
AffichageHistorique
index.php
js
index.js
index.html
server
Server.js
app.js
When I click on the button in index.html, I want to open index.php but i have the error Cannot GET /AffichageHistorique/index.php and I don't see how to fix the problem.

Here:
this.app.get('/', function(req, res) {
… you wrote a handler for what happens when the client tries to get /.
You haven't written one for /AffichageHistorique/index.php.
server.app.use('/client', express.static(__dirname + '/client'));
… comes close, but since your URL doesn't start with /client, it doesn't get hit.
Even if it did, it wouldn't execute the PHP.
The static module is for serving static files, not for executing PHP.
If you're using PHP, then consider using a server that PHP is designed to work with (like Apache HTTPD or Lighttpd).

Related

Node.javascript get on local host

I'm trying to follow a video but still can't get when I load by local host in the web browser.
I am get a console log of listening at 3000 but it seems that this line:
"app.use(express.static("/Users/name/Desktop/Weather App/public/app.html"));" is not working.
Any suggestions?
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("listening at 3000");
});
app.use(express.static("/Users/name/Desktop/Weather App/public/app.html"));
This the code Im using now.
server.js
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.sendFile(
"/Users/name/Desktop/Weather App/public/app.html"
// "/Users/name/Desktop/Weather App/public/style.css"
);
});
// serve any HTML files located in /Users/name/Desktop/Weather App/public
// app.use(express.static("/Users/name/Desktop/Weather App/public"));
app.listen(3000, () => {
console.log("listening at 3000");
});
app.html
<!DOCTYPE html>
<html>
<head>
<title>Weather App</title>
</head>
<body>
<h1>Weather App</h1>
<div id ="container">
<p>
Place: <span id = "places"></span><br/><br/>
Temperature: <span id="temperature"></span>&degC<br/><br/>
Feels like: <span id="feels"></span>&degC<br/><br/>
Minimum Temp: <span id="min"></span>&degC<br/><br/>
Maximum Temp: <span id="max"></span>&degC<br/><br/>
Humidty: <span id="hum"></span>&percnt;<br/>
</p>
<div>
<input id="inputter" type="text" ></input><br/><br/>
<button id="entButton">Click here for weather forecast</button><br/><br/>
<button id="geoEnter">Click here for fast weather</button><br/>
</div>
</div>
<div>
</div>
<script href="/Users/name/Desktop/Weather App/server.js"></script>
<script src="/Users/name/Desktop/Weather App/public/app.js" ></script>
<link href="/Users/name/Desktop/Weather App/public/style.css" rel="stylesheet" type="text/css"/>
</body>
</html>
any suggestions?
If you just want app.html to show when http://localhost:3000 is the URL, then you can do this:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.sendFile("/Users/name/Desktop/Weather App/public/app.html");
});
app.listen(3000, () => {
console.log("listening at 3000");
});
If you have more files in /Users/name/Desktop/Weather App/public that you want to automatically serve to the client when requested, then you can add this:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.sendFile("/Users/name/Desktop/Weather App/public/app.html");
});
// serve any HTML files located in /Users/name/Desktop/Weather App/public
app.use(express.static("/Users/name/Desktop/Weather App/public"));
app.listen(3000, () => {
console.log("listening at 3000");
});
So, if styles.css was located in /Users/name/Desktop/Weather App/public, then a URL for /styles.css would automatically serve the file /Users/name/Desktop/Weather App/public/styles.css.
Change the links in your app.html page to this:
<script src="/app.js"></script>
<link href="/style.css" rel="stylesheet" type="text/css"/>
The URLs in these tags need to be relative to the directory specified in your express.static() file and will usually start with a / so they are independent of the containing page URL.
The file system path supplied to express.static is too long.
express.static takes a directory path argument, not a file path. If the get request to the static server endpoint does not include a filename on the end (e.g. ".../app.html) express static middleware looks for a configurable default file name (initially set to index.html) for content to serve.
See also express.static documentation and in particular the index and extensions properties of the options object.

Can't load/find files on server with node.js, 404 error (not found)

I'm trying to load a script.js and a style.css file on the server. The index.html and index.js work fine, however, there seems to be an error when I try to load the style.css file and script.js file, which I use for backend.
GET http://localhost:4000/script.js net::ERR_ABORTED 404 (Not Found)
All my files are in the same directory, /public.
I already checked the CSS file, and it loads when I display the HTML file when it's not on the server.
This my index.js file:
const express = require('express');
const cors = require('cors');
const fs = require('fs')
const ytdl = require('ytdl-core');
const app = express();
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))
app.use(cors());
app.listen(4000, () => {
console.log('Server works at port 4000');
});
app.get('/', function(req,res){
res.sendFile(__dirname + '/index.html');
});
app.get('/download', (req,res) => {
var URL = req.query.URL;
res.json({url:URL});
})
The HTML file:
<!DOCTYPE HTML>
<html lang="en">
<head>
<link href="/style.css" rel="stylesheet" type="text/css"/>
<meta charset="UTF-8">
<title>PyTube</title>
</head>
<body>
<h1>PyTube</h1>
<input type="url" name="yturl" class="URL-input" id="yturl" placeholder="https://www.youtube.com/watch?v=" required>
<button class="convert-button">Convert</button>
</body>
</html>
<script src="script.js"></script>
I've tried a bunch of things and trying things with __dirname and paths, but I can't find the issue or fix it.

Trying to serve static JS files Node.js, Err 404

I am trying to set up a simple node.js server to do some basic Socket.io work but when I try to serve my Static JS files I get this error:
GET https://somewebsitewithfiles.website net::ERR_ABORTED 404
Here is my server and local code:
Server:
var express = require('express');
var app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/HTML/index.html');
});
app.use(express.static('Static'))
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
})
Local:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="/Static/User.js"></script>
</body>
</html>
As you can see I have used the express static file command witch doesnt seem to be working . My file system consists of my project folder and inside that is my Server JS file. There is also folder in there called "Static" that has has my static files and a folder called HTML that has my index.html
any help appreciated. Thanks
app.use(express.static('Static'))
try putting this line above your '/' route
code:
var express = require('express');
var app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.use(express.static('Static'))
app.get('/', (req, res) => {
res.sendFile(__dirname + '/HTML/index.html');
});
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
})
Edit:
<script src="/Static/User.js"></script>
You dont have to mention the 'static' in the src path.
Correct way:
<script src="/User.js"></script>

Cannot redirect to new page with NodeJS (Express)

For quite some time, I have been attempting to figure out how to simply redirect the user to a new page on button click with NodeJS and Express. The result of pressing the "Next page" button of the following page (index.html) is the error Cannot GET /nextpage.html. When I open the console, I see that the server responded with a 404 error. Both index.html and nextpage.html are stored in the "views" folder. Here is my index.html, server.js, and client.js:
index.html
<!DOCTYPE html>
<html>
<p>Home</p>
Next page
</html>
server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const http = require('http')
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static('public'));
app.get("/", function (request, response) {
response.sendFile(__dirname + '/views/index.html');
});
app.get("/next", function (request, response) {
response.sendFile(__dirname + '/views/nextpage.html');
});
var listener = app.listen('8080', function () {
console.log('Your app is listening on port ' + listener.address().port);
});
client.js
$(function name() {
$('#button').click(function() {
$.get({url: '/next'}, function(data) {
console.log("Next page requested.");
});
});
});
You are doing wrong in HTML.
In HTML your anchor tag href is "nextpage.html" which is not a valid route. So it will throw 404.
Clicking on the anchor tag is doing 2 things
Triggering Js onclick event.
Default nature(going to href value)
Default nature on redirecting of the anchor will go to 'http://localhost:8080/nextpage.html'
You can solve this like following.
<!DOCTYPE html>
<html>
<p>Home</p>
Next page
</html>

Emitted value cannot be added to DIV express.js socket.io

I have the following app.js
var express = require('express');
var app = express();
// var responseHandlerRouter = require('./routes/responseHandlerRouter.js');
routes = require('./routes');
var server = app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
io = require('/usr/local/lib/node_modules/socket.io').listen(server);
app.use('/', routes(io));
routes.js
var express = require('express');
var router = express.Router();
module.exports = function (io) {
// all of this router's configurations
router.get('/login', function (req, res, next) {
io.emit('notification', 'news');
res.end('well finally I am here');
});
return router;
}
index.html
<!doctype html>
<html>
<head>
<script src="http://127.0.0.1:3000/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000/login');
socket.on('notification', function (data) {
console.log(data);
});
</script>
</head>
<body>
<ul id='messages'></ul>
</body>
</html>
When I do a get on the URL, it should emit but its not happening. Its not showing any errors, but fails silently.
Is there anything wrong?
Update
I want to show the "news" in the div.
but I am not able to append this as follows
.... socket.on('notification', function (data) {
$('#messages').html(data);
});
</script>
</head>
<body>
<ul id='messages'></ul>
</body>....
Will make this eligible for bounty
Looks like you are using the router in a wrong way.
Not sure, but I think that app.use('/login', routes(io)) instead of what you've got should do the trick.
In your implementation your router receives only GETs to '/'
EDIT: although the answer is accepted, the real solution is in the comments below (wrong connection url specified)

Categories

Resources