I'm having trouble serving up static content such as JavaScript in Nancy.
For example using the self hosting sample I have added a test.js to the Views folder and added a
<script type="text/javascript" src="test.js"></script>
tag to the staticview.html page. If I view this page in the browser the JavaScript is executed correctly.
However when I run the sample the JavaScript is not executed. If I view the page in FireBug I see that I'm getting a 404 error for test.js.
I've tried adding
Get["{file}"] = p => { string path = string.Format("Views/{0}", p.file); return Response.AsJs(path); };
and when I set a break point and execute Response.AsJs(path) in the immediate window I get a StatusCode of NotFound
I've also tried adding a StaticContentConvention such as
protected override void ConfigureConventions(NancyConventions conventions) { base.ConfigureConventions(conventions); conventions.StaticContentsConventions.Add( StaticContentConventionBuilder.AddDirectory("/", "Views")); conventions.StaticContentsConventions.Add( StaticContentConventionBuilder.AddDirectory("Views", "Views")); }
What am I doing wrong?
To serve static files for Go 1.12+ in the standard environment, you define the handlers in your app. yaml file using either the static_dir or static_files elements. The content in the static files or static directories are unaffected by the scaling settings in your app.
Yes, Javascript files are static data as far as the web server is concerned, since the web server is just serving the Javascript file as is, it doesn't interpret or run it*.
You can configure static content using NancyConventions
. Using the code from the following bootstrapper you can place all of your static contents (css/js/html/etc) inside a folder named "static" at the root of your application.
namespace Application { public class ApplicationBootstrapper : DefaultNancyBootstrapper { protected override void ConfigureConventions(NancyConventions nancyConventions) { nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("Static", @"Static")); base.ConfigureConventions(nancyConventions); } } }
After this is done you can access static content such as scripts
<script type="text/javascript" src="/static/test.js"></script>
or css
<link rel="stylesheet" type="text/css" href="/static/styles.css">
You do not have to configure any conventions if you do not have special reasons.
Nancy ... is shipped with a default convention that will look for files in the
content
path of your application.From NancyFx | Managing static content
I achieved the same by just doing this:
<script type="text/javascript" src="content/test.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With