Require not defined - node.js

I'm trying to learn expressjs.
I have a script inside the public/javascripts folder with a require call.
The browser is reporting that require is not defined.
How can I solve it?

require() is something that you use with expressjs on your server in your nodejs code, not in your browser pages.
Scripts in your browser pages are generally loaded with <script> tags, though there are loading libraries that can be used to provide require() like functionality in the browser, but those are not needed to use expressjs for your server.
Probably your solution is to use a <script> tag in the web page to specify the script you want loaded in that web page and to add some express.static() routes in your expressjs code to instruct your nodejs server to serve the scripts in the script directory to your web pages.
With more detail about what you're trying to do, a more specific answer could be provided.
I'd suggest reading about Serving Static Files in Express.

Related

Are the security implications of installing NodeJS in the public HTML folder?

I'm running NodeJS for my server-side javascripting, but serving my pages with Apache.
My pages currently reference Socket.IO locally, in that they load the node_modules/socket.io-client/dist/socket.io.js from the /var/www/html
The NodeJS index.js file also resides in /var/www/html which has become a problem for me.
Can I move my NodeJS index.js file to var/www so it is no longer publicly accessible, without needing to move node_modules from var/www/html which Socket.IO is relying on to be publicly accessible?
When using Node.js to serve the Webpage:
Your servers root directory is typically not publicly visible. Requests to your server get handled by the routes you set up in the index.js file. By default, no files are accessible. However, if you need a public folder (e.g. for the favicon file or an index.html file), I would recommend creating a subfolder in your root directory and use for example express to make it available.
When not using Node.js to serve the Webpage:
If you need Node.js for client-side logic, you should just use normal javascript (for example this in the case of WebSockets). Node.js is a serverside application where you run javascript on the server. So on the client-side, there is no need for Node.js. If you need certain npm packages, SubStack on GitHub has a module called node-browserify. It will compress and bundle your modules and deliver it as a single js file, but you use it just like Node.js.
If you need Node.js for server-side logic, then there is no need to make it publicly available and you should change your current server configuration to not make it accessible from the browser.

Angular Universal Deployment

I would appreciate if someone could clarify if it is necessary for hosting server to have node.js support in order for Angular Universal to work. And will I need to upload both browser and server folder in dist to the hosting. If yes, any recommendations on hosting a which offer such support? Secondly is there another way apart from node.js to make server side rendering to work?
Before answering this question, lets understand some basics of SSR and CSR in a layman language.
CSR or Client-side rendered
When a web-application gets rendered on the browser (Client-side). Here browser downloads all the html css and js first. Than the JS(your-some-awesome-framework) runs on browser and decide how the final webpage will look and act.
SSR Server-side Rendering
When a web-application gets rendered on the server (Server-side). Here the JS(your-some-awesome-framework) does most of its work on server already. So on your browser you gets the webpage without any delay of your JS booting and binding and rendering.
Now there are two types of rendering -
Dynamic SSR and Static Pre-rendering SSR
Dynamic SSR
when a live server dynamically generate and serialize the application. When a user hit a URL of website , the server first generates the webpage and serve the content.
Static Pre-rendering SSR
when there is already a pre-rendered static files and the browser simple serve those files.
Now comes the answers to your question in regard to angular framework.
Is it necessary for hosting server to have node.js support in order for Angular Universal to work ?
For Static Pre-rendering SSR - NO, there is no such need.
For Dynamic SSR - technically Yes, see below
And will I need to upload both browser and server folder in dist to the hosting ?
For Static Pre-rendering SSR - browser folder on any server which can host files
For Dynamic SSR - server folder on a nodeJs support server.
is there another way apart from node.js to make server side rendering to work?
There are some ways to run node through ASP.NET
Core and other options too. But for dynamic ssr nodeJs will come the the way.

Serving StyleSheet and JS with Sails

I am a newbie at working with nodeJS and especially with the framework Sails.
I did my research and found that with sails you just need to put CSS-files under the the folder "assets" and call them directly with the URL, e.g. if I put the file custom.css in the folder "assets/foo" I should be able to access it via the URL "localhost:1337/foo/custom.css".
The problem is that my local server throws a 404 Error not being able to find the files, but strangely when I deployed the app to Heroku it works perfectly and I am able to access the css files.
Why is this not working locally?
Welcome to Sails! CSS is served automatically if you put it in your assets/styles folder. Your JS should be in assets/js folder as well. This way you can access it like localhost:1337/assets/js/myjs.js.
In your view - if you don't want to serve it everywhere with a layout - just put your tag like this: <link rel="stylesheet" href="/styles/myawesomestyle.css"> or <script src="/js/mypowerfuljs.js"></script>.
Remember, everything in assets will be made publicly available.
I really recommend that you read the docs HERE.

Changing localhost server files are served from using Node (Webstorm /maybe IntelliJ)

I'm not sure what I'm missing here, so hopefully someone can help me out. I'm working on a project where we're using Node and in the Run/Edit configurations I've down the following:
Node interpreter: This is the path to the node.exe file
which I checked out from Subversion
Working directory: this is where the "app.js" file is, this is the
path that from the command line you type node app.js and it starts the server
JavaScript file: app.js This is the name of the file that actually creates the server
Now from the main nav bar when I do Run / Run my server the box at the bottom pops up and tells me that Express server is listening on port 3000. Cool.
I can navigate to localhost:3000/myPage.html and I can get to the page just fine.
I added as JSON file to the same directory on my hard drive that myPage.html is in, and I can navigate to that as well by localhost:3000/largeTestData.json.
So the server is up and running and serving file as it should. My problem is that in my Webstorm project, I want to make an AJAX request to that largeTestData file. I do so using jQuery like:
var data = $.get('localhost:3000/largeTestData.json');
data.done(function(data){
console.log('here is your data');
cnosole.log(data);
})
When I do that I get the error (in Chrome)
XMLHttpRequest cannot load localhost:3000/largeTestData.json. Cross origin requests are only supported for HTTP.
and so I look at the URL and I'm seeing:
http://localhost:63342/
Obviously Webstorm has started the server correctly, but when I view an HTML file, it's not using that server (which, of course is why I'm getting the CORS error.
There's some fundamental stuff here which I'm obviously not getting. I need my IDE to deploy to the Web server that it started up, but it's not doing that. Please, someone give me a once over on all the technologies that I'm missing out on here.
WebStrom didn't start your node.js server, but serves static pages by its own internal HTTP server which doesn't know anything about node.js and Express.
The main problem:
When you start your node.js server, it's serving JSON files on port 3000. If you open an HTML-page with the little menu in WebStorm (where you can choose the browser), WebStorm opens the browser with an URL pointing to its own internal webserver running on a different port (e.g. 63342). JavaScript security prohibits loading data from a different host/port Same-origin policy.
It's not WebStorm's fault and you need a solution for this problem in production or you can't go live.
General Solution:
Either you have to ensure that HTML pages and JSON data come from the same host+port, or you can circumnavigate with (a) setting server-side headers ('Access-Control-Allow-Origin: *') as #lena suggested, or (b) using JSONP. Below you find some thoughts using nginx as a reverse proxy so from browser's point of view all requests go to the same host+proxy. It's a very common solution, but as mentioned above, there are other options.
Primitive solution:
Don't use WebStorm to open your browser. Load the page from http://localhost:3000/ and change the URL of the REST resource to $.get('/largeTestData.json'). You'll miss some comfort from your IDE, but you can immediately see that your program is working.
Comfortable solution:
As #lena suggested, there is a way to configure your Express/node.js as a server known to WebStorm. I haven't tried it, but I suppose you can then just press the Run-button and maybe the node.js plugin in WebStorm is as intelligent to know the static-maps in Express and know how to map an HTML-file to a web application URL and open the page in the browser with the URL served by your node.js application. (I'd be surprised once again if this really works magically, but maybe you can configure a mapping from files to URLs manually, I don't know.)
Dirty solution
With some options you can disable security checks, at least in Google Chrome. Then it's possible to load JSON data from a different port than your HTML page. I wouldn't recommend using these options (just my opinion).
Additional Hints
If you do more than just playing around with node.js and some UI fun and you have to serve your application "production-ready", then have a look at nginx to serve your static files and reverse proxy node.js requests from there. I'm using this setup even for development and it works like a charm.
Of course node.js / Express is able to serve static files as well, but IMO placing something like nginx in front of node.js (clustered) bring a bunch of advantages for production sites, e.g. load-balancing, ssl-offloading, avoid JSONP, in many cases performance, easier deployment updates, availability.
To get your code working, just change the URL in $.get() to full URL (including protocol):
var data = $.get('http://localhost:3000/phones.json');
In Webstorm 2016.3 (and probably earlier) there is now another option. Under the Configuration Settings for NodeJS runs, one can manually set the page and port to be loaded via Webstorm's "Browser/Live Edit" settings.
See the screenshot below for settings one can change.

How to render css in nodejs?

So in node.js I render the html page which is included in view/index.html. I also included a css stylesheet in the head tags, but it's not rendering. Is there anything I should know about how this should be formatted in the file system: for example, does there have to be a style folder or something for the css to be in?
Thanks.
You will need an endpoint that serves the CSS file, or use a static directory. If you are using Express, the following code when configuring the app will set a directory which will be served statically.
app.use(express.static(path.join(__dirname, 'public')));
This will tell Express to serve everything in the '/public' directory as static content.
If you are not using Express, you can take a look at this question, Node.js static file server logic (using Connect middleware), which should help you.
You need to write code to actual respond to the HTTP GET request the browser will issue for the stylesheet and send back the CSS data. Basically however you are serving view/index.html it will be similar but with a different URL, different content-type header, and different static file to send in the response. You posted no code, so you get English instead of JavaScript.
What are you using to serve the page at view/index.html? Are you simply using fs to read in the file and then sending the contents of the file in response to the request? Or are you using a middleware framework like Connect or Express? Can you provide a link to the site that you are working on, and the relevant extracts of your JavaScript code?

Resources