Blazor server app cannot access the static content of the subproject - javascript

I've created
a Blazor Server app (BlazorServerApp)(.Net Core 3.1)
a .NET Standard Class Library (MyClassLibrary)
I've added the MyClassLibrary project to the dependencies of the BlazorServerApp. Then I've added wwwroot folder to the MyClassLibrary project and added test.js file to this folder.
I've edited the MyClassLibrary project file as follows:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<AssemblyName>MyClassLibrary</AssemblyName>
<RootNamespace>MyClassLibrary</RootNamespace>
</PropertyGroup>
<ItemGroup>
<EmbeddedResource Include="wwwroot\**\*.js" LogicalName="blazor:js:%(RecursiveDir)%(Filename)%(Extension)" />
</ItemGroup>
</Project>
Blazor web app call the UseStaticFiles method in Startup, which enables static files to be served:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
I've added the test.js as <script src="_content/MyClassLibrary/test.js"></script> in the _Host.cshtml (BlazorServerApp project):
#page "/"
#namespace BlazorServerApp.Pages
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>BlazorServerApp</title>
<base href="~/" />
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
<link href="css/site.css" rel="stylesheet" />
</head>
<body>
<app>
<component type="typeof(App)" render-mode="ServerPrerendered" />
</app>
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.server.js"></script>
<script src="_content/MyClassLibrary/test.js"></script>
</body>
</html>
However, when I run the BlazorServerApp project the error appears in the browser:
GET https://localhost:5001/_content/MyClassLibrary/test.js net::ERR_ABORTED 404
That is, the web app doesn't find such a resource at the specified path.
Can anyone explain why this is happening and what needs to be done in order for the application to access static resources (such as js or css) in other dependent projects (net standard class library in my case)?

Open the component project properties and go to package tab.
You must set a value in Package id
Then you use this id to specify the path
<script src="_content/package_id/test.js"></script>

I know this was about two years ago, but I found an answer to this.
If you are running your app in Development, chances are you are finding your static web assets just fine. But, if you change your ASPNETCORE_ENVIRONMENT to anything else you will find you get a bunch of 404 errors when trying to get your assets.
To work around this add StaticWebAssetsLoader.UseStaticWebAssets(builder.Environment,builder.Configuration); to your main Main method, or your Program.cs in .net 6.
I found this information here on the aspnetcore github. They talk more about the static asset loader here which is where I found how to use it, but the issue on 38212 seemed to be unrelated. I didn't do a deep dive on how the static asset loader worked though, or why it's needed.

Related

Javascript: Changing script type to "module" fails to fetch authenticated route [duplicate]

This question already has answers here:
Javascript ES6 modules not passing along .htaccess basic authentication
(2 answers)
Closed 3 months ago.
I have an express server that serves static HTML/JS files along with a REST API. Some of the routes to the static files requires authenticated request (via Bearer JWT token). I needed to change the type of the script to module in one of the HTML files to import another script, however after doing this the browser is not able to load the script anymore as it fails to bypass the authentication middleware.
Example:
<html>
<head>
<link rel="stylesheet" href="index.css" />
<script src="index.js" defer></script>
</head>
</html>
index.js:
import {foo} from "../another-script.js"
window.onLoad(() => foo());
The server is able to fetch the index.js (however it fails on line 1 since it is not of type module)
If I change it to:
<html>
<head>
<link rel="stylesheet" href="index.css" />
<script src="index.js" type="module"></script>
</head>
</html>
It fails to fetch the index.js and instead fetches the "Not Authenticated" HTML page.
What is going on here? Why does changing the type to module mean that it is unable to import a protected route?
As answered by #napubza in Javascript ES6 modules not passing along .htaccess basic authentication adding crossorigin to the script tag worked.

Socket.io - socket.io.js not available

I need to get a socket.io server running using python.
I followed this example:
https://tutorialedge.net/python/python-socket-io-tutorial/
With the final files looking as follows:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<button onClick="sendMsg()">Hit Me</button>
<!--WORKS:-->
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>-->
<!-- DOESNT WORK:-->
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script>
const socket = io("http://localhost:8080");
function sendMsg() {
socket.emit("message", "HELLO WORLD");
}
socket.on("message", function(data) {
console.log(data);
});
</script>
</body>
</html>
server.py
from aiohttp import web
import socketio
sio = socketio.AsyncServer()
app = web.Application()
sio.attach(app)
async def index(request):
with open('index.html') as f:
return web.Response(text=f.read(), content_type='text/html')
#sio.on('message')
async def print_message(sid, message):
print("Socket ID-: " , sid)
print(message)
await sio.emit('message', message[::-1])
app.router.add_get('/', index)
if __name__ == '__main__':
web.run_app(app)
So much this is only copy paste and thus works fine, but I dont want to use the script from some online source. So I tried to modify the src of the script by commenting out the running version and replacing it by a version using a local socket.io.js.
As I did not find the script on my machine I found the following questions, that both did not help me solve my issue:
node-js-socket-io-socket-io-js-not-found
socket-io-not-being-served-by-node-js-server
No matter what I do I get the following error in my browser:
GET http://localhost:8080/node_modules/socket.io/socket.io.js net::ERR_ABORTED 404 (Not Found)
(index):18 Uncaught ReferenceError: io is not defined
at (index):18
(anonymous) # (index):18
From what I understood from the 2 linked threads, my server should provide the socket.io/socket.io.js when listen is called on the server.
Unfortunately this is not happening in my case.
I had socket.io installed via pip, I also tried npm install socket.io --save as suggested, this gives me a new folder 'node_modules', but modifying the src for my script to:
<script src="http://localhost:8080/node_modules/socket.io/socket.io.js"></script>
doesnt help either.
For some reason using the fie from cdnjs works just fine (see my index.html).
I would be very glad if someone could help me out with this.
Cheers
Chris
I've never worked with AIOHTTP (always worked with flask-socketio) so I did some research using the documentation. It turns out that like a lot of http server, AIOHTTP doesn't serve static files out of the box.
You will thus need to take care of it using the add_static method (doc here).
(Note that if you want to deploy this app for production it would be better practice to use an HTTP server like Apache or Nginx).
Just add this line under your routes declarations.
app.router.add_static('/static/', path='static/')
Now you need to create a static folder in the root of your project and put your socket.io.js file inside of it.
Make sure that the socket.io.js in the version 2.2 (same as the CDN version). You can get this file by downloading it directly from the CDN URL you were using or using npm -i -s socket.io-client#2.2. You can then find the socket.io.js file in node_modules/socket.io-client/dist.
You now just need to use <script src="/static/socket.io.js"></script> in your HTML to import socket.io.

jsreact - GET http://localhost:8080/manifest.json 404 (Not Found)

I'm trying to make my existing react application progressive by adding among other things a manifest.json.
However it seems that my application is unable to find my manifest.json file as I get the above error message and Cannot GET /manifest.json when I take a look at the developer tool's network tab . This is strange since my manifest.json is located at the root of my application, exactly where the error says it cannot find the file.
I tried several things like placing a manifest.json file in every directory or introducing a json-loader in my webpack configuration but nothing worked.
Where I reference the manifest
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="manifest" href="/manifest.json" >
</head>
<body>
<div id="root" class="body"></div>
</body>
</html>
In addition I'm using webpack-manifest-plugin which creates an asset-manifest.json file in my build directory that maps my index files.
webpack.config
//...
const ManifestPlugin = require("webpack-manifest-plugin")
module.exports = {
plugins: [
new ManifestPlugin({
fileName: "asset-manifest.json"
})
//...
created asset-manifest.json
{
"index.js": "index.bundle.js",
"index.html": "index.html"
}
I hope you can help me
The problem is not only with manifest.json but with all json files. As it says here: https://stackoverflow.com/a/29633038/3231884 , you need to setup the web.config according to the following example:
<?xml version="1.0"?>
<configuration>
<system.webServer>
<staticContent>
<remove fileExtension=".json" />
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
</configuration>
Afterwards, you should make 'npm run build' copy it to the build folder by following these steps (credits to Liviu Costea):
https://medium.com/hackernoon/adding-web-config-to-react-projects-3eb762dbe01f
change extension manifest
from manifest.json to manifest.txt
It should be an issue of manifest.json file.
Please show the contents of manifest.json file.
Try this, In manifest.json
the name property should be in small letters and contains no spaces.

Firebase function - How to include external style.css in index.js

External style.css file is not working after deploying on server
My index.js and styles.css is in same directory.
index.js
const functions = require('firebase-functions');
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send(
`<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
Hello ...
</body>
</html>
`);
});
Cloud Functions HTTP triggers do not serve static content (such as HTML, CSS, and JS files) by default. HTTP triggers are primarily intended for you to write code that responds to HTTP requests, like API calls.
If you want to serve static content along with HTTP requests, you should look into using Firebase Hosting along with Cloud Functions. Firebase Hosting will serve your static content, and when configured properly, it will also forward some URLs to Cloud Functions that can be serviced by code you write.
Your other option is to configure an express app in Cloud Functions, and set up some routes with it so that incoming requests that go directly to Cloud Functions can be served by content that you deployed with your functions. But I think using Firebase Hosting is probably the more common and useful option.

Deploy angular (hottowel) app in apache httpd

I've generated a project with john papas hottowel.
gulp serve-build
is working.
When I drop the build folder to my apache server the app is not working. It's not finding the files, although they are there.
localhost/:15 GET http://localhost/styles/lib-7947d5e2c5.css
localhost/:17 GET http://localhost/styles/app-ba4747fbb6.css
localhost/:34 GET http://localhost/js/lib-e827a87368.js
localhost/:36 GET http://localhost/js/app-9e5293691e.js 404 (Not Found)
The index.html is found.
<head>
...
<link rel="stylesheet" href="styles/lib-7947d5e2c5.css">
<link rel="stylesheet" href="styles/app-ba4747fbb6.css">
</head>
<body>
...
<script src="js/lib-e827a87368.js"></script>
<script src="js/app-9e5293691e.js"></script>
</body>
What can be wrong?
You will need to turn off HTML5 Mode and change base URL.
Turn off HTML5 mode in app/blocks/router-helper.provider.js.
Line 18: $locationProvider.html5Mode(false);
Comment out base in index.html
Line 17: <base href="/">
By doing this your web app will route to a 404 by default. To fix this you can change the core route to / instead of /404 within app/core/core.route.js
By doing this you will get a #/ within your URL.

Categories

Resources