I have a router like so
r := mux.NewRouter()
r.PathPrefix("/static/styles/").Handler(http.StripPrefix("/static/styles/",
http.FileServer(http.Dir("static/styles"))))
book := r.PathPrefix("/books").Subrouter()
book.HandleFunc("/issued-books/", IssuedBooks)
book.HandleFunc("/top-trending/", ShowTopTrending)
book.HandleFunc("/", ShowAllBooks)
book.HandleFunc("/available/", ShowAvailable)
r.HandleFunc("/", ShowHome)
http.ListenAndServe(":8080", r)
The basic handler function structure is below:
func ShowAvailable(w http.ResponseWriter, r *http.Request) {
tmp := Store{}
for ix, val := range JSON.Books {
status := &val.IssueStatus
if *status == false {
tmp.Books = append(tmp.Books, JSON.Books[ix])
}
}
renderTemplate(&w, "available.html", &tmp)
}
renderTemplate is defined like so :
func renderTempate(w *http.ResponseWriter, filename string, tmp *Store) {
path := "static/" + filename
tmpl := template.Must(template.ParseFiles(path))
buf := new(bytes.Buffer)
if err := tmpl.ExecuteTemplate(buf, filename, *tmp); err != nil {
http.Error(*w, err.Error(), http.StatusInternalServerError)
return
}
mime.AddExtensionType(".css", "text/css; charset=utf-8")
res := *w
res.Write(buf.Bytes())
res.(http.Flusher).Flush()
}
The first Issue is it never renders the css file correctly....the browser always ends up saying ....
Refused to apply style sheet from /path/to/css.... because its MIME type ('text/plain') is not a supported stylesheet MIME type....and i tried using the MIME package to set it correctly just before sending the processed template to the client but it still wont work.
The Second Issue is the HTML rendering becomes inconsistent....only the ShowAllBooks page displayed, others didn't,
giving a 404 error...for this i tried removing the forward slash from the URL paths and it all pages displayed...so the forward slash affects the page rendering...any help is deeply appreciated
Remove ending slashed for routes:
book.HandleFunc("/issued-books", IssuedBooks)
book.HandleFunc("/top-trending", ShowTopTrending)
book.HandleFunc("/", ShowAllBooks)
book.HandleFunc("/available", ShowAvailable)
css is supported by GO out of the box - https://github.com/golang/go/blob/master/src/mime/type.go#L60
Check what exactly server returns for for css links. Could it be 404?
Related
At first, I saw a topic Symfony Twig and xml - Document is empty error and my case is similar, but provided answers there, did not help me.
So my problem is: sometimes I got parsing error in a browser.
In chrome it is:
This page contains the following errors:
error on line 38 at column 21: Opening and ending tag mismatch: link line 19 and head
Below is a rendering of the page up to the first error.
But on firefox things get a little bit more accurate? (I got non-english version so here is my translation of this error):
Error parsing XML: wrong tag. Expected </link>
So my guess is, Symfony somehow provide XML document to the browser, instead of HTML.
But looking at the source code, or even at Inspector, there is nothing that would indicate XML. I got <!DOCTYPE html> tag at start, and proper tags.
When this error occur document in Inspector in Chrome is parsed, like <LINK> tags should have end tags (</LINK>) and everything under this tag is considered as be inside this <LINK> tag. But message in Firefox gave me answer: XML document, so <LINK> tag is treated like tag with closure.
But what is more important, this happening only sometimes, not always. For most of the time I got good looking website, with everything working, all tags parsed, all assets loaded, Javascripts working well.
Why this could happen that sometimes, Symfony put XML file instead of HTML to a browser?
I have an idea, that this could be because of HTTP-CACHE I have inserted in my app in the controller action. Maybe I configured something in a wrong way.
Or maybe there is something else wrong in here? Maybe in other YAML configuration file?
public function index()
{
$categories = [ ... ];
$articlesByCategory = [ ... ]; // is readed correctly - checked
return CacheService::buildCachedResponse($this->render('pages/home.html.twig', [
'categories' => $categories,
'articles' => $articlesByCategory,
...
]), self::CACHE_TIME);
}
class CacheService
{
public static function buildCachedResponse(Response $response, int $expirationSeconds)
{
$response->setPublic();
$response->setMaxAge($expirationSeconds);
$response->headers->addCacheControlDirective('must-revalidate', true);
return $response;
}
}
class CacheKernel extends HttpCache
{
protected function getOptions(): array
{
return [
'default_ttl' => HttpCacheTimesPerController::DEFAULT,
];
}
}
Kernel switched to "CacheKernel" in "public/index.php", as showed in Symfony documentation.
INFO: currently app is running on symfony 5.x, and php 7.4.
I've had a few errors trying to render single blog posts.
I tried using the page template with /post/{post_name} and I was getting this error:
warn Non-deterministic routing danger: Attempting to create page: "/blog/", but
page "/blog" already exists
This could lead to non-deterministic routing behavior
I tried again with /blog/{post_name}.
I now have both routes, which I'm not sure how to clean up; but more importantly, on those pages, nothing renders, even though there should be an h1 with it's innerhtml set to the node.title and likewise a div for the content.
I've uploaded my config and components to https://github.com/zackrosegithub/gatsby so you can have a look.
Not sure how to fix
I just want to see my content rendered on the screen.
Developer tools don't seem to help when there's no content rendered as I can't find anything to inspect to try to access it another way.
Thank you for your help
Your approach is partially correct. You are using a promise-based approach but when using then() you are already settling and partially resolving it so you don't need to use the callback of resolve(), which may be causing a duplication of the promise function so try removing it.
Additionally, you may want to use a more friendly approach using async/await functions. Something like:
exports.createPages = async ({ graphql, actions, reporter }) => {
const yourQuery= await graphql(
`
{
allWordpressPost {
edges{
node{
id
title
slug
excerpt
content
}
}
}
}
`
if (yourQuery.errors) {
reporter.panicOnBuild(`Error while running GraphQL query.`);
return;
}
const postTemplate = path.resolve("./src/templates/post.js")
_.each(yourQuery.data.allWordpressPost.edges, edge => {
createPage({
path: `/post/${edge.node.slug}/`,
component: slash(postTemplate),
context: edge.node,
})
})
})
// and so on for the rest of the queries
};
In addition, place a console.log(pageContext) in your postTemplate to get what's reaching that point and name the template as:
const Post = ({pageContext}) => {
console.log("your pageContext is", pageContext);
return <div>
<h1>
{pageContext.title}
</h1>
</div>
}
export default Post;
I have a SPA, I want to use routing for ng-view.
I have the code included in a page at domain.com/folder/dashboard.aspx
This is just a piece of that existing page, I can't move it elsewhere.
When I use route /list it alters my url to domain.com/folder/list/ which works, but breaks the ability to refresh the page (and gives a 404 since dashboard.aspx is not a default page, nor can it be)
How can I keep the url as domain.com/folder/dashboard.aspx/list?
I did try to setup my routes as dashboard.aspx/list and other various similar adjustments, but didn't have any luck.
Just like what #Claies said, it should be handled in your server config, just gonna drop my route config here in case you haven't tried this yet
var routeWithoutResolving = function (template: string, title?: string, style?: string) {
var name;
var slashIdx = template.indexOf('/');
if (slashIdx !== -1) {
name = template.substring(0, slashIdx);
template = template.substring(slashIdx + 1);
} else {
name = template;
}
var templateUrl = '/folder/' + template + '.aspx/';
return {
templateUrl: templateUrl,
title: title,
style: style,
area: _.capitalize(name),
page: template,
reloadOnSearch: false
}
}
Usage
.when('/domain.com/folder/dashboard.aspx/list', routeWithoutResolving ('folder/dashboard.aspx'))
I figured it out.
You can't use HTML5 mode, you have to be using Hashbang.
I set my routes as normal, /list and /list/item
For my links, I just used full urls, with the Dashboard.aspx#!/list/item and /list
I also removed the base tag from the html page
My problem is that the backend server (written in grails) is automatically converting my request URL to be a different URL. Specifically, it is changing it from /UXChallengeAwards/processSelectedNotifications to /UXChallengeAwards/index.
--
In a template gsp file, I have defined a button that makes a jQuery ajax call when clicked on:
<button class="blue-link"
onclick="jQuery.ajax({type:'POST',
data:jQuery(this).parents('.multiSelectForm').serialize(),
url: '/ici/UXChallengeAwards/processSelectedNotifications/${challenge.id}',
success:function(data,textStatus){},
error:function(xhr,textStatus,errorThrown){}
})" >
The method UXChallengeAwardsController.processSelectedNotifications exists. It performs some work and then redirects to another action in the controller. In fact, this used to work. But somehow in the process of adding a second button I made a change which seems to have broken things.
When the button is now clicked, the request URL gets switched to /ici/UXChallengeAwards/index and a 404 is returned because index does not exist as an action in this controller.
I've googled, and the most common answer for when this happens is that a controller must return some results for the view. But I've seen plenty of examples of redirects in controllers, and I do not see what I am doing wrong. (I did try variants of rendering results, but with no success.)
Here is what my controller action looks like:
def processSelectedNotifications = {
def challenge
def checkboxes = params.list('selectCheckbox');
for (checkbox in checkboxes) {
// the checkbox contains the id of a ChallangeAward that should be published
ChallengeAwards challengeAwards = ChallengeAwards.get(checkbox.toInteger())
if (challengeAwards) {
// grab a challenge for use in the redirect, they are all the same
challenge=challengeAwards.challenge
publish(challengeAwards)
}
}
if (challenge) {
redirect action: 'challengeAwardsRemote', id: challenge.id
return
}
// render a failure message if we got here
render messageNS(code:"UX.ChallengeAwards.Publish.failure")
}
I would really appreciate any insights into what might be wrong, or how to go about tackling this issue. I've checked my UrlMappings, and this is the rule that should handle this controller/method request:
"/$controller/$action?/$id?"{ constraints {} }
Thank you very much!
I'm going to go ahead and answer my own question, in case it is helpful for other newbies.
It turns out that I was not getting an automatic redirect. Rather, I had an error in the button setup code, so that grails was using its default link behavior. (Which is to go to the controller that matches the view, and if no action is specified, use the index method.)
The code above was originally created using a remoteSubmit tag, but I found that the generated code did not support handling multiple forms on a single page very well. So, I copied that generated code and then tweaked it to handle the multiple forms. However, I wanted the styling to match up with what was already in place on the page, so I switched it to be a button. That's when things went awry.
Eventually, I ended up specifying an onClick function for the button, and then writing the ajax submit code in javascript. Which turned out to be much simpler.
Here is what the button specification ended up looking like:
<button type="submit" id="notifications" class="blue-link" >
<i class="fa fa-envelope-o"></i>
<g:messageNS
code="UX.DiscussionBoard.ChallengeAward.Button.notify" />
</button>
And the associated JavaScript:
jQuery(document).ready(function() {
var clkBtn = "";
jQuery('button[type="submit"]').click(function(evt) {
clkBtn = evt.target.id;
});
jQuery('.multiSelectForm').submit(function() {
var url = '/ici/UXChallengeAwards/processSelectedNotifications';
if (clkBtn == 'deletes') {
url ='/ici/UXChallengeAwards/processSelectedDeletes';
}
var errorTarget = jQuery(this).parents().find('.recipientMessage').val();
var requestData = jQuery(this).parents('.multiSelectForm').serialize();
var options = {
data : requestData,
type : 'POST',
url : url,
target : '#awardsTab',
error : function(data) {
jQuery('#' + errorTarget).html(data.responseText).show();
},
success : function(data) {
console.log("in success");
}
};
jQuery(this).ajaxSubmit(options);
return false;
});
I'm using Meteor's router package and everything works fine when I try to render the groupCreate template under the /createGroup URL like this:
Meteor.Router.add({
"/createGroup": {
to: "groupCreate",
and: function() {
return Session.set("currentGroupId", null);
}
}
});
However, the template is not drawn when I try to use a nested URL like /groups/create instead of /createGroup. I would like to understand why. Do nested URLs carry a special semantic?