Can't reference public folder from node.js deployment with firebase - javascript

After watching Node.js apps on Firebase Hosting I tried to create a project with Polymer and NodeJs/express and firebase hosting.In the linked Video it is shown that firebase would serve by default the static public/index.html file which is why they remove it to then serve a dynamic one. However, this particular file is in the same functions directory and not anymore placed in the public folder.Does this mean that my whole project should be placed in the functions folder or just the app entry-point? I am not able to send a file that is placed in my public folder as shown below.
project
functions
server.js
public
index.html
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '/public/index.html'));
})
I believe firebase is hosting the public and the function folder differently or am I referencing just wrong?

You'll need to nest your public folder inside the functions folder to be able to reference files from it in your functions. You can do this just by changing the public setting in firebase.json to be e.g. functions/public and then moving the directory inside functions.
You would then be able to do something like you're describing.

I think no need to move entire public folder into functions folder. You can use the relative path like this
app.get('*', (req, res) => {
res.sendFile( './../public/index.html'));
})
It worked for me... try this.

Related

how to access static file from same directory in express?

i am trying to access the static file from the same directory but it is not working problem is it isn't loading the image in the live server
app.use('/static',express.static('/public'))
Here public is the main directory where I creat 'css'& 'img' folder and put my 'js' and 'html'file.
Before I used to access the file out side of the same directory from where I creat a css and img folder & inside those folder I creat a 'css' file and put a image . on that time it was working properly but when I put my 'js' and 'html' in the same directory where I creat my 'css' and 'img' folder it is not working means server is creating but in the 'HTML' file the 'image' is not loading in the live server.
hear is the code:
const express= require('express')
const app= express()
app.use('/static',express.static('/public'))
app.set('view','./public/view')
app.get('/',(req,res)=>{
res.send('user accessed')
})
app.listen(5000,()=>{
console.log("server is running at 5000")
})
Firstly, if you want to hear right answer you need to provide as more as possible information about your problem. For example, you need to provide at least folder structure of your app, files which you want to include to your app and paths which you use. And another point for you, why not to use best-practice solution which suggested by node js express creators? Here is express app generator https://expressjs.com/en/starter/generator.html . If you keep to use the best practice solution then you will not have such questions.

Serving UI in express.js after logic

I understand how to return a file using express with:
res.sendFile(path.join(__dirname, 'fileName.html'))
And I understand how to serve up a folder using:
app.use('/customAPI', express.static('folderName'));
using the documentation here.
The folder with the UI is created using angular 4 build. So, it all goes into one folder creating a index.html and a bunch of *.bundle.html files.
However, I don't understand how to serve up a the UI after doing some logic. For example:
router.get("/", function (req, res) {
let myParam = req.query.whatever;
if (whatever) {
res.redirect('//google.com'); //this works fine
}
else {
//I don't know what to do here
app.use("/somePath", 'dist'); //won't work because what do I put in "somePath"?
res.sendFile(path.join(__dirname, '../../dist/index.html'));
//^ this only serves up the file but fails because it can't find the library files that index.html needs to load.
}
});
I've tried going down the road of trying to use res.render but I'm not 100% sure if that is what I'm looking for.
Question: How do I serve up a folder containing all ui information correctly
When you serve a specific path these are sending the content only for that path, for example an HTML with the interface, the HTML file can make calls to other files, like CSS, JS etc ...
You need to serve the static files in a public folder
app.use('/static', express.static(path.join(__dirname, 'public')))
All files in the static folder will be served in the url /static/filename
In the html of the path, you must include the resources of the static folder that you need

JS File outside www root folder

I would like to know how to access or create a javascript file outside www root folder in .net core project created in visual studio 2017. i have created a file in the folder where my views are but i can't able to access the file.
The point of the root directory is to expose files over HTTP.
If the file isn't exposed over HTTP, then it doesn't have a URL.
If it doesn't have a URL, the browser can't request it.
Move the file into the root directory.
ASP.NET exposes all your static filse from the wwwroot folder. It's advisable to put your files there 99% of the time. However, If your project really requires that you put your javascript file in the views folder (and I don't see why), you can create a middleware.
your middleware just has to be an extension method for the IApplicationBuilder interface
for this, you can create a static class like so
// your middleware (static class so it can have extension methods)
public static class MyStaticFileServer
{
//static method (IApplicationEnvironment so we can easily get the full path of our Project)
public static IApplicationBuilder UseJsFiles(this IApplicationBuilder app, IApplicationEnvironment env)
{
//
var path = Path.Combine(env.ApplicationBasePath, "/Views/Js")
var provider = new PhysicalFileProvider(path);
var options = new StaticFileOptions();
//so our middleware only responds when the url begins with "/Views/js"
options.RequestPath = "/Views/Js";
// file provider so we can serve files
options.FileProvider = provider
//use static file middleware to our middleware to serve files from whatever folder we specify
app.UseStaticFiles(options)
return app;
}
}
Now you're done with the middleware to serve static files from a folder of your choice. Now, we ned to invoke our middleware from the startup class. We do this by invoking it in the configure class in the Startup class
//ASP.NET Configure Method in the Startup.cs file
public void Configure(IApplicationEnvironment environment)
{
app.UseJsFiles(environment);
}
You can actually do this in .net core natively.
I'm assuming you have the static files middleware up and running already, but just incase, run the following in your nuget package manager :
Install-Package Microsoft.AspNetCore.StaticFiles
Inside your startup.cs, you will have a Configure method. It probably looks not too dissimilar to the following :
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
So the UseStaticFiles will serve things from the wwwroot. But you can actually add multiple uses of the same middleware in the pipeline. So consider the following :
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), #"content", #"js")),
RequestPath = new PathString("/content/js")
});
app.UseMvcWithDefaultRoute();
}
Here we serve static content from the wwwroot as per normal, but we also want to say that the file location of /Content/Js should be served as well. You can add as many of these as you like and serve static content.
More info
http://dotnetcoretutorials.com/2017/04/28/serving-static-files-outside-wwwroot-asp-net-core/
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files

How to include static files in express js

I am using the the express js framework with node js and in my server.js file , i have used
app.use('/api',router);
In my ejs file , when i use a script tag
<script src = main.js>
I get an error "Cannot get http://localhost:3000/api/main.js"
How can i include these files in the ejs
please help!!!
in app.js you have to add static folder directory access
app.use(express.static(path.join(__dirname, 'public')));
in public folder add your folders files
--public
----javascript
----css
----img
inside javascript add your main.js
and in ejs add
<script src = "javascript/main.js"></script>
You can use express.static middleware
app.use('/public', express.static('directory/containing/your/files'));
The parameter of express.static is the path to the directory containing all your files that you wish to make static (the path that you provide can be relative to the directory where you launch your node process, or an absolute path), the directory should be available in your file system.
Then you can require your resources like: <img src='/public/imagesA.jpg'>
The '/public' mount path is optional, but recommended
You serve static files through an included middleware in Express - express.static('folder/with/resources'). You do so by adding it to the middleware chain using app.use.
Let's say you want to serve your static files located in the local folder /dist through the public URL /static.
import express from 'express';
const app = express();
app.use('static', express.static('dist'));
Read more about it here.

node-static cannot serve a folder above current folder

I don't know if this is a limitation to node-static or is it a bug in my code, but I can't seem to get it to serve files above or beyond the current directory. My current directory structure is this:
project
public
...public stuff here...
system
core
server.js
server.js lives in core directory, making the path to public as ../../public - but this code won't run. It returns a 404.
staticServer = new (static.Server)('../../public');
webServer = http.createServer(function (request, response) {
staticServer.serve(request,response);
})
webServer.listen(appServerConfig.port, appServerConfig.address);
However, if I change the structure to make the public folder live beside server.js and change the code accordingly, it works:
project
system
core
server.js
public
...public stuff here...
staticServer = new (static.Server)('./public');
webServer = http.createServer(function (request, response) {
staticServer.serve(request,response);
})
webServer.listen(appServerConfig.port, appServerConfig.address);
Why is this so?
Be aware that using relative paths will resolve those paths relative to the current working directory of the node.js process, that is, the directory you were in when you ran node server.js. So as coded, your could looks OK to me as long as you are in the core directory when you launch node. Are you sure you always launch node from the core directory?
If you want to be independent of the cwd (more robust IMHO), use __dirname to get the absolute directory path of the current file and then tack on your relative paths to that: __dirname + '/../../public'.
Beyond that, consider fs.realpath to resolve those. I can't say whether node-static in particular has special code to prevent this, but most other modules I've seen such as connect's static middleware will happily serve any arbitrary directory without special restrictions.

Categories

Resources