ASP .NET 7 run static HTML file with scripts - javascript

I am trying to return html file from my ASP NET 7 app. In that html files i am calling couple of scripts. Html file and scripts exist in same root directory:
using Microsoft.Net.Http.Headers;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// middleware
app.Use(async (context, next) =>
{
var html = await File.ReadAllTextAsync("index.html");
context.Response.ContentType = "text/html";
await context.Response.WriteAsync(html);
await next();
});
app.Run();
The problem is, that scripts are loaded with Content-Type: text/html instead of application/javascript:
My question is, how to call only .js file extensions with diffrent content type using ASP .NET?

Your middleware is currently answering every request with the index.html content. So, it doesn't matter if you are requesting the path /index.html or the path /script.js, the server will always respond with your HTML file.
If you only need to provide static files (like your HTML and JS files), you can do it by just adding the official static file provider middleware to your Startup:
using Microsoft.Net.Http.Headers;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseStaticFiles() // Static file provider
app.Run();
This will return every file included in the /wwwroot folder in the root of the project. So, if you want to return the index.html and all the related JS files, just move them to the /wwwroot directory and make a request to the path /index.html.
More information on the official Microsoft documentation: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-7.0

Related

How to run/view ExpressJS server for webpages other than index.html?

So, I want to view/run/display webpages other than the index.html from my public folder which has multiple html files using ExpressJS and NodeJS. Every time I run my server, I can only view the index.html file. Is there a way I can access other html files? I am a beginner and just getting started with the backend part.
This is my app.js
app=express();
const path=require('path');
const Router=express.Router();
const port=process.env.PORT||3000;
require("./db/connectdb");
const static_path=path.join(__dirname,"../../frontend/public");
app.use(express.static(static_path));
app.get('/createelection',(req,res)=>{
console.log("Create an Election here");
});
app.listen(port,()=>{
console.log('Server is running at port no. '+ port);
});
My Public Folder
Public
-index.html
-createelection.html
-voterlogin.html
From a comment on the question:
localhost:3000/createelection
By default the static module will:
Give you index.html if you ask for a path ending in /
Give you the file you ask for
You are asking for createelection but the file is named createelection.html.
With your current code you need to ask for http://localhost:3000/createelection.html.
Alternatively you can tell Express to try to autocomplete the file extension for you. Look at the documentation for the static module:
extensions: Sets file extension fallbacks: If a file is not found, search for files with the specified extensions and serve the first one found. Example: ['html', 'htm'].
The setting defaults to false
So you would need:
app.use(express.static(static_path, { extensions: true }));

Sending multiple Files or folder using node.js Express

So my problem is i was originally serving my files i believe static using
app.use(express.static(clientPath));
Since then i realised i need to get some pentameters from the connecting url.
now when i use the connection as below i only get the index.html so there is no css with it or any images so i was wondering how i can send all my files in the client folder?
app.get('/username/:userID/hash/:hash', function (req,res) {
var userDetails = {
username : req.params.userID,
hash : req.params.hash
}
res.sendFile(path.join(__dirname + '/../client/index.html'));
});
Continue to use the static module to serve static files.
Make sure that the URLs you use to reference CSS, images, etc are still correct (since the URL of the HTML document has changed so relative paths will resolve differently).

Access a local directory to retrieve files from localhost and write back

I currently have an Angular app (MEAN Stack) that I am running locally on my Windows machine. Being new to Node/Express, I would like to be able to access a local directory from http://localhost:3006 that I have setup within my main app directory, called /myfiles which I am unsure how to do.
What I am unsure is, how do I create an endpoint to access and read these files from localhost within the /myfiles directory and display them within an Angular Material dialog?
Just not sure what I need to do as part of Express side (setting up the route) and then the Angular side (using HttpClient) to display.
Further to the above, I will also need to write back to the /myfiles directory, where I will need to perform a copy command based on a file selection within Angular.
You'll want to create an endpoint in Express that your Angular app can call to be served the files.
I'll assume the files you want to read and send are JSON files. Here's a really simple example of an endpoint that you can visit that will return the file to your frontend.
In your Angular code you will make a get call to /myfile
var fs = require("fs");
app.get('/myFile', (req, res) => {
var filepath = __dirname + '/myfiles/thefile.json';
var file = fs.readFileSync(filepath, encoding);
res.json(JSON.parse(file));
});
Then in Angular, you'll have something like
http.get('/myfile').subscribe( (data) => { console.log("The data is: ", data) });
ADDED
The example I provided above was just the basics to answer your question. Ideally, in production for file paths, you should the Node path library which 'knows' how to behave in different environments and file systems.

Sending whole folder content to client with express

I made an html5 game (using GameMaker), which is constituted of an index.html and a folder "html5game" that contains the dependencies of the game - the javascript code and the resources. The problem is the resources are quite numerous and diverse (sounds, sprites, etc.) and The client needs them all to play.
I am looking for a way to send them all without naming them specifically.
I tried the glob module :
var glob = require( 'glob' );
var files = glob.sync( './html5game/**' ).forEach( function( file ) {
require( path.resolve( file ) );
});
but I can't figure a way to send the files using res.sendFile() once I did that.
I tried
var express = require('express');
var app = express();
[...]
app.get('/aeronavale/jeu', function(req, res){
res.sendFile(__dirname + '/aeronavale/index.html');
res.sendFile(files)
});
[...]
app.listen(3000, function(){
console.log('app started on port 3000, yeah !')
})
but it gives me the error :
TypeError: path argument is required to res.sendFile
If you have an other solution, I a also interested. Thanks for your answers !
You will not be able to send multiple file like that with res.sendFile. The most straightforward thing that you can do here would be this:
Put your index.html file and your html5game directory into some common directory, e.g. called html and put it where you have your Node.js program. An example directory layout would be:
/home/you/yourapp:
- app.js (your node program)
- package.json (your package.json etc)
- html (a new directory)
- index.html (your main html to serve)
- html5game (the directory with other files)
- (other files)
Now, in your Node program you can use something like this:
var path = require('path');
var express = require('express');
var app = express();
var htmlPath = path.join(__dirname, 'html');
app.use(express.static(htmlPath));
var server = app.listen(3000, function () {
var host = 'localhost';
var port = server.address().port;
console.log('listening on http://'+host+':'+port+'/');
});
This will serve all of your files (including index.html) on addresses like:
http://localhost:3000/ (your index.html)
http://localhost:3000/html5game/xxx.js (your assets)
Of course you still need to make sure that you refer to your assets in your index.html file correctly, for example with:
<script src="/html5game/xxx.js"></script>
in the case of the example layout above.
The top level directory with your static assets (where you have your index.html) is usually called static, public or html but you can call it whatever you like, as long as you use the correct path in your call to express.static().
If you want to have your game available in some path other than the root path then you can specify it to app.use. For example if you change this:
app.use(express.static(htmlPath));
to this:
app.use('/game', express.static(htmlPath));
Then instead of those URLs:
http://localhost:3000/ (your index.html)
http://localhost:3000/html5game/xxx.js (your assets)
those URLs will be available instead:
http://localhost:3000/game/ (your index.html)
http://localhost:3000/game/html5game/xxx.js (your assets)
A lot of questions here are related to serving static files with Express so I made a working example and posted it on GitHub so that people could have a working starting point and go from there:
https://github.com/rsp/node-express-static-example
See also some other answers where I talk about it in more detail:
How to serve an image using nodejs
Failed to load resource from same directory when redirecting Javascript
onload js call not working with node
Loading partials fails on the server JS
Node JS not serving the static image
The workaround for this is to compress the directory using the archiver library and uncompress it on the front end.

Node.js : Load .js and .css files included in HTML file without Express/frameworks

How can you load the .js .csv and .css files included within an HTML file, displayed with Node.js? (Without frameworks like Express)
E.g. <script src="clock.js"></script>
In Firefox, it shows that the page, fs.readFile('./index.html'), is requesting clock.js, jquery.js, etc. as html files, probably because of response.writeHead being text/html.
Is there a way to do:
if file included in index.html = .js
set writeHead to application/javascript
if file included in index.html = .css
set writeHead to text/css
Without specifying in advance what files index.html may include? (e.g. if in the future, index.html also uses menu.js, you wouldn't need to update the node.js script)
Is there a way to see what files are being requested by index.html, then modify the headers of those files (e.g. .js has application/javascript)?
Is this the sort of thing you are looking for?
var http = require("http");
var fs = require("fs");
var path = require("path");
var server = http.createServer(function(request, response) {
//typically what will happen here is that you will see
//see the request for the page (index.html?) first and
//then the browser's subsequent requests for js, css etc files
var url = request.url;
var file = //do something clever to extract the file name from the url ( url.split("/")?)
var html = fs.readFileSync(file,"utf-8");
//probably want to check the file extension here to determine the Content-Type
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
});
server.listen(8081);
console.log("Server is listening");
A bit agricultural, and you would probably run in to all sort of problems with routing - but its the idea.

Categories