for now I exec 'ng build' and exec 'ts-node ./src/index.ts':
//////////index.ts
import * as express from 'express';
import { join } from 'path';
import { json, urlencoded }from 'body-parser';
import BaseRoutes = require("./backend/services/newService");
var app : any = express();
app.use(express.static(join(__dirname + '/../dist/')));
app.use(json());
app.use(urlencoded({extended: true}));
app.use('/api', new BaseRoutes().routes);
app.get('*', function(req, res, next) {
res.sendFile(join(__dirname + '/../index.html'));
});
app.listen(3000);
all good and work, but How to run only expressJS server, compile project by using original files only (without webpack).
in case of pushing on prod I compile project by compressed /dist/files only, otherwise I would like to work with original files
varibale __dirname is
C:\Users\AxOn\Documents\projects\techStarters\ang4Express\src
Help please
if I exec just 'ts-node ./src/index.ts' and change path as __dirname + '/index.html' I see white Display:
seems angular is not loaded.
in your package.json
{
"name": "project-name",
"version": "0.1.0",
"private": true,
"scripts": {
"start": "node ./server.js"
},
"dependencies": {...
then in your project directory at the command line do;
npm start
npm will execute whatever is in start section of your package.json file
Related
this is my firs project with electron and nodejs
I need to load a specific folder in my electron application
the final structure should be like:
Myapp.app
folder-contents
MyApp must read contents from folder-contents directory
import httpServer from './server'
function createMainWindow() {
const window = new BrowserWindow()
if (isDevelopment) {
window.webContents.openDevTools()
}
window.loadURL(`http://localhost:18081/${app.getAppPath()}/folder-contents/`)
}
in server.js
const path = require("path");
const http = require('http');
const express = require('express');
const PORT = 18081;
const app = express();
app.use(express.static(process.cwd()));
app.set('port', PORT);
const server = http.createServer(app);
server.listen(PORT, "127.0.0.1");
module.exports = app;
In my package.json
"scripts": {
"dev": "electron-webpack dev",
"compile": "electron-webpack",
"dist": "yarn compile && electron-builder",
"dist:dir": "yarn dist --dir -c.compression=store -c.mac.identity=null",
"start": "electron ."
},
launching npm run dist --mac and open myapp.app i get this error
Cannot GET /folder-contents/
any idea?
you can add your files to a folder name public and inside that you can have all your static files stored and then you need to call it in your app.js like:
app.use(express.static('public') //Public is the name of the folder and then you might be able to use all of your static files presented in that folder in your project if this didn't clear you here's a refrence if i am wrong and you get the correct answer else where please correct me.Thank you.
This is an express documentation
I am trying to run a server using es6 modules but crashes every time I do it and works whenever I use it with es5error message
I have babel installed and have "preset": ["env"] in my .babelrc file but whenever I run it, I have a "syntax error: Invalid or unexpected token". And this is not on one particular project, this is the third project where am experiencing this
import http from 'http';
import express from 'express';
import logger from 'morgan';
import bodyParser from 'body-parser';
// setting up express application
const app = express();
const hostName = '127.0.0.1';
const port = 3000;
const server = http.createServer(app);
// logs request to the console
app.use(logger('dev'))
// Parse incoming data requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
// making a request to the server
app.get('*', (req, res) => res.status(200).send({
message: 'Welcome to the default API route',
}));
server.listen(port, hostName, () => {
console.log(`Server running at http://${hostName}:${port}/`);
});
it supposed to bring out "Welcome to the default API route" to the console but instead, it is an error message. And if the repo is needed, i will gladly supply it
ES6 is not yet supported in the Node runtime by default. You can integrate it like this:
npm i esm && npm i -D nodemon
In your package.json, add this to scripts:
"start": "nodemon -r esm index.js"
(make sure the index.js part of the script matches the name of your server entry point file)
Run npm start
Solution to running nodemon with support for ES6 module import/export syntax.
first, install the esm package:
npm i esm
second, ensure package.json contains the line
"type": "module"
example package.json:
line 6
{
"name": "stack-overflow-example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"esm": "^3.2.25",
"express": "^4.18.1"
}
}
To run nodemon:
nodemon esm path-to-your/index.js
the file extension is necessary
I would like to run my app with express on a Node server.
My server.js file:
var express = require('express');
var path = require('path');
var app = express();
app.get('/', (req, res) => {
res.sendFile(path.resolve('dist/my-app/index.html'))
});
app.listen(80, () => {
console.log('Server started!')
})
But when I'm trying to view my website on localhost nothing appears. Can you help me?
Hope this would help you.
1) Run:
ng build --prod
This will create a dist folder. Used for production.
2) Run:
npm install --save express
To install express and save it as dependency in the project.
3) Create a file in root: ./server.js
4) Copy this code. Don't forget to modify with your name project
const express = require('express');
const http = require('http');
const path = require('path');
const app = express();
const port = process.env.PORT || 3001;
app.use(express.static(__dirname + '/dist/my-app-name'));
app.get('/*', (req, res) => res.sendFile(path.join(__dirname)));
const server = http.createServer(app);
server.listen(port, () => console.log(`App running on: http://localhost:${port}`));
5) To run the server.js file
node server.js
I found a solution !
const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
const port = process.env.NODE_PORT || 3000;
const root = path.join(__dirname, 'dist', 'my-app');
app.get('*' ,function(req, res) {
fs.stat(root + req.path, function(err){
if(err){
res.sendFile("index.html", { root });
}else{
res.sendFile(req.path, { root });
}
})
});
app.listen(port);
console.log('Listening on port '+ port);
You can do this in just very few steps...
1). Run ng build --prod (If you get budgets error than increase the budget in angular.json file according to the error)
2). After above command, a dist folder will be generated containing your project folder, move this project folder which is present inside dist folder from angular project in to your node project say inside public folder (public/your_build_angular_project).
3). Now in your node main file say index.js or app.js, include these lines
const path = require('path');
app.use('/', express.static(path.join(__dirname, 'public/your_build_angular_project')));
4). Now serve your node server then when you hit it, you will get your angular project running
Hope this will help you or somebody else! Thanks.
Sample angularjs app directory is here :
AngularApp->myApp->
AngularApp->myApp->controllers
AngularApp->myApp->views
AngularApp->myApp->services
AngularApp->myApp->app.js
AngularApp->myApp->index.html
Create a package.json file and insert below code in it:
(Location : AngularApp->package.json)
{
"name": "myApp",
"version": "0.0.1",
"description": "My Project",
"dependencies": {
"express": "*"
},
"engine": "node >=0.6.x",
"scripts": {
"start": "node server.js"
},
"main": "server.js",
"repository": {
"type": "git",
"url": ""
},
"author": "myApp",
"license": "myApp",
"bugs": {
"url": ""
},
"homepage": "/"
}
Create server.js:
(Location: AngularApp->server.js )
var express = require('express');
var app = express();
app.use(express.static("myApp")); // myApp will be the same folder name.
app.get('/', function (req, res,next) {
res.redirect('/');
});
app.listen(8080, 'localhost');
console.log("MyProject Server is Listening on port 8080");
Run commnad 'npm install' after navigating to package.json file.
Run command 'npm start'. Open a browser and hit localhost:8080/
/styles.css goes missing after I do a page refresh.
Here's my package.json build script:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"clean": "rimraf dist",
"start": "nodemon -e js,css,handlebars -i scss --watch app --exec babel-node app/app.js",
"build": "npm run clean && mkdir -p dist && babel app -s -D -d dist",
"serve": "node dist/app.js",
"postinstall": "npm run build"
},
The problem only exists in the dist version.
I run npm run build, then npm run serve.
What this does is build and copy every file to /dist folder.
App is served in /dist/app.js.
So /styles.css loads on initial load, but subsequent loads shows request is cancelled. Tried loading the site with a private window but the problem persists. It loads only once again, after reloading the server.
screenshot of request
Here's app.js:
import bodyParser from 'body-parser'
import express from 'express'
import exphbs from 'express-handlebars'
import path from 'path'
import sassMiddleware from 'node-sass-middleware'
const PORT = process.env.PORT || 3000
const app = express()
// Config
app.locals.config = require('./config.json')
// Views and handlebars view engine
const hbs = exphbs.create({
defaultLayout: 'main',
layoutsDir: 'app/views/layouts',
helpers: {
sitename: function () {
return app.locals.config.sitename
},
ga: function () {
if (process.env.NODE_ENV === 'production') {
...
}
},
},
})
app.engine('handlebars', hbs.engine)
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'handlebars')
// Body parser
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
// Sass middleware
app.use(sassMiddleware({
src: path.join(__dirname, 'public/scss'),
dest: path.join(__dirname, 'public/css'),
outputStyle: 'compressed',
sourceMap: true,
}))
// Static folder
app.use(express.static(path.join(__dirname, 'public')))
// Routes
app.use(require('./routes/index.js'))
const server = app.listen(PORT, () => console.log(`listening at port ${PORT}...`))
I load /styles.css with this in my view template:
<link rel="stylesheet" href="/styles.css">
Update and solved:
I should had added that my folder structure looks like this:
/app
- public/
- css
- js
- scss
- routes/
- ...
- views/
- ...
Solved the problem by changing the the src path in views template:
<link rel="stylesheet" href="/css/styles.css">
Had to add prefix to node-sass-middleware too for local development.
// Sass middleware
app.use(sassMiddleware({
src: path.join(__dirname, 'public/scss'),
dest: path.join(__dirname, 'public/css'),
prefix: '/css',
outputStyle: 'compressed',
sourceMap: true,
}))
I am new to Nodejs and I am following a course on Pluralsight for Nodejs using express.
I have the following code:
var express = require('express');
var app = express();
var port = 5000;
app.use(express.static('public'));
app.get('/', function (req, res) {
res.send('Hello World');
});
app.get('/books', function (req, res) {
res.send('Hello Books');
});
app.listen(port, function (err) {
console.log('running server on port ' + port);
});
And then from the command line I run the following:
$ npm start
This is my json file:
{
"name": "library",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.14.0"
}
}
Now the problem I am having is that when from my browser I put: localhost:5000 everything looks fine. I see my Hello World text. But when I am trying to go to a folder under the public such as localhost:5000/css/style.css I get the following error message.
Cannot GET /css/style.css
And here is my folder structure
If you want:
localhost:5000/css/style.css
to be served by:
app.use(express.static('public'));
Then, you need to make sure that style.css is in:
public/css/style.css
where public/css/style.css is evaluated relative to the current working directory.
You don't disclose your file hierarchy, but if localhost:5000/css/style.css isn't working, then apparently style.css isn't located properly in public/css/style.css or your public directory isn't in the proper place.
app.use(express.static('public')); tells express to look for requested files relative to the public directory. So a request for /css/style.css will be looked for at public/css/style.css.
Also, app.use(express.static('public')); assumes that the public directory you want it to look in is relative to the working directory when the app.use() statement is run so you need to either make sure that is also correct or you need to put an absolute path in the express.static() statement so you don't depend on the current working directory.