Vue-resource can't load express static file - javascript

So, I have a bit of a problem. Here's my server.js
require('dotenv').load();
const http = require('http');
const path = require('path');
const express = require('express');
const app = express();
const server = http.createServer(app).listen(8080, () => {
console.log('Foliage started on port 8080');
});
app.use(express.static(path.join(__dirname, '/public')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
What this does, is that for every /whatever it gives the index.html file. Alongside that, it serves static files from /public Now, my index.html looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Foliage</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/foliage.css" media="screen" title="no title">
<script src="https://use.fontawesome.com/763cbc8ede.js"></script>
</head>
<body>
<div id="app">
<router-view :key="$router.currentRoute.path"></router-view>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script src="js/md5.js"></script>
<script src="js/cookies.js"></script>
<script src="js/dragula.js"></script>
<script src="js/build.js"></script>
</body>
</html>
All of the JS files and the style files are loaded appropriately from public/jsand public/css for this. However, in build.js, which is a webpack-ed vuejs app, I use vue-resource, to load in another file from public/themes/Bareren/templates. That looks like this
page = {};
page.Template = "Index";
this.$http.get('themes/Barren/templates/'+page.Template+'.html').then((response) => {
console.log(response.body);
});
However, this request does not give me the file in public/themes/Barren/templates. It instead gives back the site's own index.html file. How could i fix this?

app.use(express.static(path.join(__dirname, '/public')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html')); });
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html')); });
Try to console.log(path.join(__dirname, '/public')) and console.log(path.join(__dirname, 'index.html') to see if the path matches what you are expecting.
this.$http.get('themes/Barren/templates/'+page.Template+'.html').then((response)
=> {
console.log(response.body); });
You can also try console logging your get request. Usually I need to play with the pathing to making sure I'm serving the correct files.

One thing you can try is to define a GET route which responds with your template before the wildcard at the bottom.
app.get('/themes', (req, res) => {
// get the theme name
res.sendFile(path.join(__dirname, ... ));
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});

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.

node js res.render does not work, but res.send does

I am setting up the environment for a node js app. But the views/ejs files are not being rendered.
If i do:
app.get("/", function(req, res){
res.send('Hello');
});
it works.
But if i do:
app.get("/", function(req, res){
res.render("welcome");
});
it doesn't.
my app.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const indexRoutes = require("./routes/index");
const userRoutes = require("./routes/user");
const ejsLayouts = require("express-ejs-layouts");
const path = require("path");
mongoose.connect("mongodb://localhost/userAuth", function(err, res) {
if (err) throw err;
console.log("Connected to database");
});
//EJS
app.set('view engine','ejs');
app.use(ejsLayouts);
app.use(express.static(__dirname + '/public'));
app.set('views',path.join(__dirname+'/views'))
//ROUTES
app.use("/", indexRoutes);
app.use("/user", userRoutes);
app.listen(3000, function() {
console.log("server started");
});
my index.js file (userLogin/routes/index.js)
const express=require("express");
path = require('path');
router= express.Router();
router.get("/",function(req,res){
res.render("welcome");
});
module.exports = router;
my folder structure
userLogin
/..
/routes
/index.js
/views
/welcome.ejs
I have an h1 element olny in welcome.ejs file.
Looking at the code you provided, in index.js you are trying to render a view called check, when the only view you have is called welcome. Your paths and routes look to be correct, rendering the correct view should work.
app.engine('html', require('ejs').renderFile);
if u woudlike to render .html files
then
fs.readFile(path.resolve(__dirname + '/../public/views/logs.html'), 'utf-8', (err, content) => {
let renderedHtml = ejs.render(content, {'user': req.session.db}); //get redered HTML code
res.end(renderedHtml);
})
you should have views/layouts/layout.ejs file if you are using express-ejs-layouts npm
inside app.js :
const ejs =require('ejs');
const ejsLayouts = require("express-ejs-layouts");
app.set('view engine','ejs');
app.use(ejsLayouts);
app.set('layout', 'layouts/layout');
layout.ejs file has common layout that follow all files
if you are using bootstrap then your layout.ejs file would be like :
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<title></title>
</head>
<body>
<?- body ?>
</body>
</html>
so now other ejs pages will only have content to display
like welcome.ejs file is
<h1>Welcome Page</h1>

Displaying Contents of Mongodb Database on webpage

I am trying to display the contents of my database on a webpage.
The way I want to do it is by displaying the content in the database by descending order. I have made the connection to MongoDB and am able to see my data in the terminal stored correctly. I just can't seem to figure out how to display that stored data now.
Thanks!
Server.js file.
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: true })
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/node-demo");
var nameSchema = new mongoose.Schema({
Alert: String
});
var User = mongoose.model("User", nameSchema);
app.listen(3000, function() {
console.log('listening on 3000')
})
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html')
})
app.get('/alertview', (req, res) => {
res.sendFile(__dirname + '/alertview.html')
})
app.post('/', urlencodedParser, function (req, res) {
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
User.find({},function(err,docs){
console.log(docs);
})
Html file I want to display the alerts on.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="/alertpageStyle.css" media="screen" />
<meta charset="UTF-8">
<title>View Alerts</title>
</head>
<body>
<div class="header">
<h1>Current Alerts</h1>
</div>
</body>
</html>
Simple example using the EJS templating, essentially you pass your object to the template at the time of rendering. You can also iterate over data. Same approach can be used for Handlebars or Mustache packages.
var express = require('express');
var path = require('path');
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/', index);
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
</body>
</html>

Can't load static files in index.html

I'm trying setup simple app with node, express and angular2. The problem is that, when I run localhost, open it in browser, I get errors: "Uncaught SyntaxError: Unexpected token <". I think it happens because of incorrect path or wrong code in my node/express files.
For example, when I'm trying open library file in source, I always get index.html code :
Here is the folder structure:
Below I'll show full code
index.js
'use strict'
// require dependencies
let express = require('express');
let bodyParser = require('body-parser');
let path = require('path');
// require our custom dependencies
let router = require('./router');
let app = express();
const PORT = process.env.PORT || 4000;
// get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//share folder with static content
app.use(express.static(__dirname + '../frontend/build'));
app.use('/', router);
app.listen(PORT, function() {
console.log('Example app listening on port', PORT);
});
router.js
let express = require('express');
let router = express.Router();
let path = require('path');
let User = require('./models/user');
router.use(function(req, res, next) {
console.log('request to', req.path);
next();
});
router.route('/users')
.get(function(req, res) {
User.find(function(err, users) {
if (err) {
res.send(err);
}
res.json(users);
});
});
router.get('*', function (req, res) {
res.status(200).sendFile(path.resolve('frontend/build/index.html'));
})
module.exports = router;
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Angular 2 App!</title>
<base href="/">
<!-- load the dependencies -->
<script src="./assets/libs/core-js/client/shim.min.js"></script>
<script src="./assets/libs/zone.js/dist/zone.js"></script>
<script src="./assets/libs/reflect-metadata/Reflect.js"></script>
<script src="./assets/libs/systemjs/dist/system.src.js"></script>
<script src="./systemjs.config.js"></script>
<script>
System.import('app').catch(function(err) {
console.error(err);
});
</script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
Thanks!
Update
I changed in router.js from this
router.get('*', function (req, res) {
res.status(200).sendFile(path.resolve('frontend/build/index.html'));
});
to this
router.get('/', function (req, res) {
res.status(200).sendFile(path.resolve('frontend/build/index.html'));
});
and now I have 404 error, files not found

Categories

Resources