I am new to node.js/express.js and I am reading some tutorials. I am confused because I am used to the simple apache logic, node.js/express.js logic confuses me. Please help me.
This tutorial uses the default express routes to add/get data from a db. But, at the begging , at the part named "PART 2 – OK, FINE, LET'S DO "HELLO, WORLD!" edits the ...\ROUTES\INDEX.JS file to add just a simple html page. Why is that?
Can I just use the public folder to serve my files and access the by using the same URL?
If I have like 50 files, I have to add 50 similar functions to my ...\ROUTES\INDEX.JS so I can serve them ? Even the simplest static files ?
Can I just put all my files in the public folder and then edit app.js and ...\ROUTES\INDEX.JS ?
Also I was reading the first chapter of the book Jump Start Node.js by Don Nguyen. It does not edit routes, just adds methods to the app.js and implements new modules (named db and user) for adding users to the db. This also adds a new get function to app.js for a simple form.html file.
Again, why can I use the public folder and then edit the app.js and create my own modules?
Again, If I have like 50 files, I have to add 50 similar functions to my app.js so I can serve them ? Even the simplest static files ?
Finally,
What is the difference between the two methods ? In which case I use them ?
Which one is the best practice ?
Thank you very much
To serve the folder named "public" as static files:
app.use(express.static(__dirname + '/public'));
The reason the tutorial did not put their 'simple' index page into public, is that their 'simple' page is not static. They pass in the data { title: 'Express' } to the dynamic page.
If the title 'Express' is always going to be static, then yes you can serve it from public. However for the sake of the tutorial, we assume they might dynamically change the title from 'Express' to something else.
Related
Sorry for the wording in the question. Probably my biggest issue with this is not knowing how to phrase it correctly, as I've not been able to gleam a single hint of an answer from google.
Using api routes in Next.js I want to serve a data.json file. This works no problem, however I also want to be able to edit this file afterwards and for the api to reflect the updated content. As it stands after building and running if I edit the file the api still returns the old one, hell I can even delete it. I assume this is because Next.js makes a copy of the file at build time, and puts it somewhere in the .next directory(?), haven't been able to find it there though.
Below is a boiled down version of what I'm doing:
/pages
/api
/info.js
/data
/data.json <- file I want to use with the api
pages/api/info.js
export default function (req, res) {
const data = require('../../data/data.json')
// Do stuff
res.status(200).json(data.something)
}
Any guidance on this is very appreciated
Using require to include a file in any Node app will definitely tie the json file to the apps run time or build time.
The feature you describe sounds like static file serving but next caches those files as well.
Try reading the file in the API instead
const fsp = require('fs').promises
export default async function (req, res) {
try {
const file_data = await fsp.readFile('../../data/data.json')
const json_data = JSON.parse(file_data)
// Do stuff
res.status(200).json(data.something)
}
catch (error) {
console.log(error)
res.status(500).json({ error: 'Error reading data' })
}
}
Actual Static files
In development you can probably work around this by triggering rebuilds when static files update.
If you want update the data files independently of a built app, they will probably need to be hosted separately to the Next build. If you are next exporting a completely static site, you might have a place to put the static files already. If not you can serve the data files with another node process, or a web server, or something like S3.
Problem :
I am new to React JS, and looking for an option to read environment configs from an external property file. This problem is more specific for one of my clients, who is looking to have an option to change the environment files dynamically. E.g. change the hostname/port dynamically whenever there is a change. The build process is not owned by my client. I create a minified final package, which my client deploys it on tomcat/web server.
Tried Solution :
With some read-outs, I have configured .env files for different environments and able to successfully read configs from these files. However, these are more of a build process environment files. And, I am trying to find a way to read the configs from an external source after my package is created.
Possible solutions : Here is one possible approach I can think of -
Read external property file using libraries like "properties-reader". I will provide the property file as part of my release bundle (i.e. build folder). My client can change this property file whenever required.
Please suggest if this is the correct approach or is there a better solution to this problem?
A Solution which worked for me !!
1) Create a "config.js" file inside public folder of react project. Sample Content of the
"config.js" file -
window.env = {
API_DOMAIN_ADDR: "http://localhost:8080"
};
2) Refer "config.js" file inside index.html. Code for index.html will be -
<body>
<div id="root"></div>
<script src="%PUBLIC_URL%/config.js"></script>
</body>
3) Now, content of the config.js file will be accessible to react code. Sample code to retrieve the value of config.js variables -
window.env.API_DOMAIN_ADDR
Add this code wherever variable value needs to be accessed. I added this in my service class which is making ajax call.
I would suggest using something like Firebase Realtime DB. I had a similar requirement for pointing the App builds to production or development server APIs for my company. For this, we use to load a Firebase Config and from there the UI used to pick up the host server endpoint.
Advantages:
This saves you from deploying your build folder every time.
This is realtime and less prone to errors.
FirebaseDB is free for small stuff like this.
The second option is to create two environment files which I see you have already done.
I'm a newbee to html/js/css.
Now I have a big frontend that use realative reference of static files that don't contain a 'static' prefix.
However Django need a STATIC_URL definition in settings.py, default is "/static/".
Then the real request url is "/demo/faces/male/16.jpg", but the url django expected is "/static/demo/faces/male/16.jpg"
It's really a big frontend maintained by other guys, I don't want to modify it.
Is there a method to remove the 'static' requirement?
See this. It says "In addition to using a static/ directory inside your apps, you can define a list of directories (STATICFILES_DIRS) in your settings file where Django will also look for static files."
The example that they give puts static in the specification of the additional directory, but that appears to be inessential. So you would just list your /demo/faces/male and /demo/faces/female/ directories.
I'm building a fairly simple experiment to run as a website.
It's all javascript, so all I need the server for is to store the experiment results. I've set up a Django server on WebFaction, but my problem is making django redirect clients to the 1st static html page (from where js takes over).
I gather my solution should be something like this (using django 1.7.1):
urls.py
django.views.generic import RedirectView
urlpatterns = patterns('',
url(r'^$', RedirectView.as_view (url='fudge.html'))
)
It works when DEBUG = True on settings.py, but when it's set to False I get:
Not Found
The requested URL /fudge.html was not found on this server.
Iv'e set STATIC_ROOT = '/AmirStatic/' in settings.py and ran python manage.py collectstatic following instructions iv'e found on the net, but this didn't do the Trick.
Either I don't understand the path settings in Django or they are not configured properly or I don't understand how static webpages are used. But I would have thought it would be much simpler than this. Iv'e spent a good 3 days losing hair over it.
I would be very thankful to anyone with good advice on this,
thanks a lot in advance.
Oh and i'm a newbie to python, Django and web-developing in general if that hasn't come across :)
When you are developing, Django can serve your statics files, but when going into production, django doesn't serve your static files (and should not, it should be handled by your reverse proxy such as nginx or apache)
Please take a look at the Deploying static files of the django documentation.
As #Mihai Zamfir suggested above-- try actually using a URL and linking to a view. Then within the view you define the logic for the template which is contained in fudge.html.
Example:
url(r'^fudge/$', views.fudge_view, name='fudge')
This is assuming you also have in your urls.py:
from your_app_name import views
Is there a way to do the following in NodeJS (or ExpressJS)?
While I understand the flexibility routing offers, I pretty much dislike the way it has to be configured. (I am no expert in Express)
For example, the application structure is as shown below:
app
-- public // has all the static files.
-- dynamic // Root level file for something that contains all the dynamic pages
-- index.nsf // NSF == node server file (Just making up a sample extension here).
// NSF files have front matter and code like shown in section below
-- posts // A directory
-- view.nsf
-- edit.nsf
-- pages
-- thankyou.nsf
-- contactus.nsf
i.e when the user goes to the url "http://mydomain.com/pages/contactus", the content from that nsf file is rendered.
The NSF that I have in mind, will probably look like below - with just some YAML front matter
---
controller: contactUsController // A javascript file
layout: contact // Jade layout or HTML layouts
---
OR with some YAML front matter and layout as the content of the file.
---
controller: contactUsController
---
extends base
h1 This is the contact us page. Fill in the details below.
Even a one time configuration to setup a middleware like below would work:
app.use(app.**some_automatic_router**);
app.use(express.static(path.join(__dirname, 'public')));
Thank you.
Maybe you are looking for something like this :
https://npmjs.org/package/dynamic-routes