creating my first nodejs,mongo, express angularjs app - angularjs

I am setting up my first angularjs webapp using nodejs.
The one part i am not sure how to do is how to include my angularapp.js in my index.html?
currently i have
/public
index.html
/javascript
webapp.js ( my angular app js file)
/routes
myroute.js
app.js (my nodejs app )
my myroute.js has and it loads fine
router.get('/', function(req, res, next) {
res.sendFile(path.resolve('public/index.html'));
});
the problem is that i am note sure how to load my webapp.js
in my index.html i have
<script src = "/public/javascript/webapp.js"></script>
And this does not load. So what is the best way to do this. Should i create
a route for everything in /public/javascript/
how do other people do this or what is the best practice
thanks for any help
update....
i added the following to myroute.js
router.get(/javascript/, function(req, res, next){
res.sendFile(path.resolve('public/javascript/webapp.js'));
});
and the javscript file now loads but this is not the way to do it.

I got it now. I've been searching and looks like for security reasons you need to serve the javascripts and other files you wish to allow access to as static files. On app.js add this :
app.use("/static",express.static(__dirname+"/public/javascript"));
Where "static" is just a virtual path you create for an specific folder. Then change src on script:
http://localhost:port/static/webapp.js
or
/static/webapp.js
It worked for me
For more details you should check this out:
http://expressjs.com/es/starter/static-files.html

Related

Express Rewriting for Clean URLs in MEAN Stack Application with no index.html

Like many other clean angular URL rewrites, upon refreshing the page on a clean URL like localhost:3000/profile I get the GET /profile 404 error. I have been trying to use an Express Rewrite to send the index.html file, but as far as I know, I don't have an index.html to send, as it's not rendered until the index.js route.
I tried the following in my app.js:
app.all('/*', function(req, res, next) {
// Just send the index.html for other files to support HTML5Mode
res.sendFile('index.html', { root: __dirname });
});
and receive Error: ENOENT: no such file or directory, stat 'C:\xampp\htdocs\healthyu\healthyu\index.html'
My directory looks like this image here, and I can see there is no index.html file in the root directory. I have tried views/index.html, views/index.ejs, and views/index with no luck, and views/index.ejs actually prompted a download when I refreshed the page.
Is there a way to use Express to successfully rewrite the URLs, or will I be more successful with a mod-rewrite in an .htaccess file?
So what I needed to do was change all of my server requests that were API requests to use the /api prefix, so get /api/posts in order to reduce conflicts with get /posts which was the original API call and view name along with other conflicts.
My index.html is generated in my express routes/index.js file so I just needed to make sure I used that file whenever I tried to navigate to a different URL than the home entry point. The relevant parts of the code looked like the following:
var index = require('./routes/index');
var users = require('./routes/users');
app.use('/', index);
app.use('/api', index);
app.use('/users', users);
app.use("/*", index);

How to serve ReactJS static files with expressJS?

The Problem
I have successfully served the index.html file of my React app, but the index.js that replaces <root> in the html file
with my first React component is not triggering on ReactDOM.render.
How do I get the index.js file to start? If my understanding of serving a React app is skewed in certain ways, I would greatly
appreciate clarification.
Folder Structure
/ - contains all server-side files, including server.js
/client/ - contains all React files
/client/build/ - contains all production-ready client files
/client/build/index.html
/client/build/static/js/main.[hash].js - seems to be a minified version of index.js that contains the ReactDOM.render for
my React app
Current Deployment
I am using Facebook's create-react-app for the /client/ directory, including npm run build to automatically populate /client/build/
File Snippets
// server.js
let app = express();
app.use(express.static(path.join(__dirname, '../client/public')));
This successfully loads the default index.html provided by
create-react-app
// index.html
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
</body>
The above section of code may/may not be useful, but it is the default
html file that comes with create-react-app. Do I need to replace the
noscript tag with a script tag that references the minified index.js
file? I have attempted that, and nothing changed, but perhaps it is
because of incorrect relative path-making.
After trying many different things through trial/error, the solution is quite simple:
Serve the /client/build folder in the static call, like so:
app.use(express.static(path.join(__dirname, '../client/build')));
I had the same problem for a while and I would say that the solution that works is divided into 2 parts to avoid problems with the routers
Server the static from the CRA build (in your case the client/build)
const buildPath = path.normalize(path.join(__dirname, '../client/build'));
app.use(express.static(buildPath));
Set a final route (after all other routers in your server) to use the following:
const rootRouter = express.Router();
/*
* all your other routes go here
*/
rootRouter.get('(/*)?', async (req, res, next) => {
res.sendFile(path.join(buildPath, 'index.html'));
});
app.use(rootRouter);
//on your react app run
npm run build
//The insert the following code on your server
const path = require("path");
app.use(express.static(path.join(__dirname,"nameOfYourReactApp","build")))
//Replace nameOfYourReactApp with the name of your app
my project structure
project
-->client
back end(express)\
after using npn run build i found out that index.html in build was using wrong directory of css files or static instead of using
const path = require('path');
app.use(express.static(path.join(__dirname, '/client/build/')));
i know i also tried ../client...... but not working
so what i did is cut and paste static folder of build in root directory this image can give you the idea, and its working structure

How to send an AngularJS file with ExpressJS?

I'm new with ExpressJS, I have a small example using EJS, but I want use AngularJS for manipulating the DOM. Both technologies offer me DOM manipulation, so why some people use it together? I don't understand.
I have no idea how to render HTML files. What is the correct way to use AngularJS with ExpressJS?
res.render('index.html');
As far as I know EJS is really for templating, none of the embedded js is executed on the client.
Personally I have found some cases where it is handy to use a templating language with AngularJS or any client side framework. For example, sometimes it is nice to be able to interpolate some csurf tokens, or session data required by the client app into your html on the server. Other times it is not necessary.
As for rendering html, use the express.static middleware. It comes with Express, you pass a file path, and it returns a handler that will serve the contents of a given directory. You could put express.static anywhere in your middleware chain, but I usually put it at the top to avoid naming issues. Read the documentation for more information.
Consider the following:
var express = require('express')
var app = express();
// Asssuming we have a directory
// `public` in the root of the application
app.use('/', express.static(__dirname + '/public'));
// now you're serving all the files in public directory off the root path
// Add middlewares and routes...
For a really simple app you could you use the fs module, and stream the contents of a file to the response. The following is naive example of how you could do this, in production you would want to listen for error events and implement some cache control.
app.get('/', function(req, res) {
res.set('Content-Type', 'text/html');
fs.createReadStream('./index.html').pipe(res);
});
Please use this :to render first time
and for more information please go her http://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})

Page reload doesn't work when removing # from angular urls

I'm trying to remove # from my angularjs urls using
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('!');
and <base href="/"> in my index.html and i have changed the hrefs in my partials from #/abc to /abc
it works fine when navigating through links within the site, however except my home page, on every other page, when i try to reload the page or copy and paste the link(and hit enter) it gives me error. i have done alot of search online with no luck. i'm hoping someone here has already gone through this and can help me.
thanks
So if you are using jade you shall do the following:
app.get('/', index);
// while index is defined in routes.js and jade is defined as template engine
If you're using angularjs templating engine with normal html files, do the following:
exports.index = function(req, res) {
res.sendfile(__dirname + "/public/index.html");
};
app.get('/', index);

AngularJS and Express Routing issue

I'm using AngularJS and ExpressJS and having an issue with routing. I saw many other posts but none of those solutions seemed to work. Here is my routes in Express:
module.exports = function(app, auth) {
//Api routes
var mycontroller = require('../app/controllers/mycontroller');
app.get('/api/dostuff/:id', mycontroller.getBlockByHash);
//Home route
app.get("/", function(req, res) {
res.render('index');
});
};
When I go to my root /, everything works as expected. ExpressJS serves up my index and angular picks up the rest. When I click a link /blocks, it works as expected since AngularJS picks up the route. But when I refresh, I get a 404 not found error.
I tried app.get('*' instead, but that gives me a completely different error where nothing loads.
I'm using Jade to create the basic page structure with Express. My Express config is:
app.use(express.favicon());
app.use(express.static(config.root + '/public'));
When using html5Mode the documentation says:
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)
What it doesn't mention is:
You should exclude static assets like scripts/styles/images/fonts etc.
You should also exclude your Restful API.
Your case:
The error you got there is express serving html into script tags and the browser fails to parse them as a valid javascript.
Use express.static to serve static assets and then use app.get('*', for redirecting all other requests to your angular.js entry point (index.html).
express.js middleware order do counts!
express.static must be declared before app.router
Node.js / Express.js - How does app.router work?

Resources