Deno - how to implement a 404 page - deno

I have been struggling to implement a 404 page in deno(oak server framework) - if i load any addtress that does not exist, i get just a blank page..
tried:
(page404MiddleWare.ts):
import {Context, exists, send} from "./deps.ts";
export const page404MiddleWare = async (ctx: Context, next: Function) => {
ctx.response.body = "404 page";
await next();
}
But that seems like a bad practise.

I would add a default route for all non existing urls and redirect user there:
router.get("/(.*)", async (context: Context) => {
context.response.status = 404;
context.response.body = "404 | Page not Found";
});
and all rest routes:
...
...
router.get(
"/api/users",
UserController.fetch,
);
router.get(
"/api/me",
UserController.me,
);
...
...
Checkout my Deno REST boilerplate project for more details:
https://github.com/vicky-gonsalves/deno_rest

The question's old, but this worked for me:
const app = new Application();
// add your middlewares here
app.use(router.routes());
app.use(router.allowedMethods());
// and then redirect to 404, if there wasn't found any route earlier
app.use((context: Context) => {
context.response.type = "text/html; charset=utf-8";
context.response.status = 404;
context.response.body = "<h1>404, Page not found!</h1>";
});
Essentially you add a custom middleware, which returns 404 after it goes through your earlier middlewares, without returning any response.
Hope it helps someone! :)

Related

Using _middleware in next-auth redirects to favicon.ico

To protect all pages on the site without authorization, I use _middleware.js.
./pages/_middleware.js
export { default } from "next-auth/middleware";
When I go to the site without authorization, I am redirected to the login form. But after I fill it out and log in, it redirects me to http://localhost:3000/favicon.ico
Why on favicon.ico I can't understand. Maybe someone will explain.
Not sure what causes this but setting a redirect callback in NextAuthOptions seems to solve it.
export const authOptions: NextAuthOptions = {
...
callbacks: {
async redirect({ url, baseUrl }) {
return baseUrl;
},
}
};

Next.js redirect www to non www

I have been trying to find a workable solution this searching google but can't find anything solid. I am hosting my Next.js application on Vercel.
When I run a seo check it moans about me having the site available on www and non www and says I should pick one and get it to redirect so in my case, if someone types in www.example.com I would prefer it left of the www.
Since I don't have a htaccess file I can do this in, how would I do it?
Not sure if it matters, but I am using WordPress as my backend aka: Headless Wordpress
You should be able to use host-based redirects now since Next v10.2. See https://nextjs.org/docs/api-reference/next.config.js/redirects#header-cookie-and-query-matching.
In next.config.js:
module.exports = {
// ...
redirects: async () => [
{
source: '/:path*',
has: [{ type: 'host', value: 'www.yourdomain.com' }],
destination: 'https://yourdomain.com/:path*',
permanent: true
}
]
}
you can easily handle permanent redirection in nextjs using the below-mentioned code.
export const getServerSideProps = async (context) => {
const { req, res } = context;
if (req.headers.host.match(/^www/) !== null) {
res.writeHead(301, {
location: "https://" + req.headers.host.replace(/^www./, "") + req.url,
});
res.end();
}
return { props: {} };
};

Posting Comments to WordPress with WPAPI

I'm using Netlify event-triggered webhooks to call a script that's designed to post a new comment to the WordPress API. I'm trying to implement wpapi to make the POST request but not sure if I'm hooked up properly.
exports.handler = async (event, context, callback) => {
let body = JSON.parse(event.body).payload
if (body.form_name == 'comment-form') {
// I assume I have to authenticate here
var wp = new WPAPI({
endpoint: 'https://example.com/wp-json',
username: 'username',
password: '123456'
});
...
I then form the data to pass in... From what I can tell from the WordPress REST API, I can pass in a name, comment, and a post id. I'm not sure if I'm missing a parameter as I can't find any documentation about required params.
// url encode - not sure if this is required
let comment = {
author_name: encodeURI(author_name),
author_comment: encodeURI(author_name),
post: body.data.postId
}
I then try calling wp.comments().create() passing in the object and setting up a callback:
wp.comments().create(comment, function(args) {
console.log(args) }
).then(function( response ) {
console.log( response );
}).catch(function (err) {
console.log(err);
});
I am using this function in a Gatsby project and am utitlizing gatsby-source-wordpress to pull data from a WordPress site, if that makes any difference.
When I run this function in Netlify, in the function log, there is no response or error message.
Thanks

Angular2 http get result empty for custom post types wordpress toolset

I am using wordpress rest api and angular2 to build simple one page app. I created a custom post type with toolset. All is working fine and I can see the data returning fine.
http://tncorp.biffapps.com/wp-json/wp/v2/downloads/?filter[product]=Pico
Screenshot
When try to request the data in my Angular application, the response body is empty.
Response
_body
:
"[]"
headers
:
Headers
ok
:
true
status
:
200
statusText
Does anyone know why this is happing?
Code for the http get:
getProductDownloads($id): Observable<any> {
this.ProductsDownloads = this.http.get(this.wpurl + 'downloads/?filter[product]='+$id)
.map(res => {
console.log('GET DOWNLOAD',res)
return this.ProductsDownloads = this.extractData(res)
})
.catch(this.handleError);
return this.ProductsDownloads;
}
You want to return the Observable itself:
getProductDownloads($id): Observable<any> {
return this.http.get(this.wpurl + 'downloads/?filter[product]='+$id)
.map(res => {
console.log('GET DOWNLOAD',res)
return this.ProductsDownloads = this.extractData(res)
})
.catch(this.handleError);
}
Then when you're calling it, you subscribe to the Observable.
// I'm using "this" here, but if you have it in a -service- you'd put that there
this.getProductDownloads(id).subscribe(result => {
this.products = result;
});
Also, you could do it the following way and incorporate the | async pipe in your template instead of manually subscribing & unsubscribing.
this.products = this.getProductDownloads(id);
// template:
{{ products | async }}

Spark-java redirect - browser does not redirect

Ok, so I try to follow Spark documentation and I want to perform simple redirect in my Single Page Application. My code looks like this:
post("/users/login", (req, res) -> {
ObjectMapper mapper = new ObjectMapper();
User creation = mapper.readValue(req.body(), User.class);
User user = userService.getUser(creation.getLogin());
if (user.getPassword().equals(creation.getPassword())) {
req.session().attribute("userid", creation.getLogin());
System.out.println("OK");
res.status(201);
res.redirect("/index.html");
return "";
}
System.out.println("BAD");
return null;
} , json());
Basically, I have three static html files: registration.html, login.html and index.html. I read stuff concerning staticFileLocation so I added at the beginning of main function following line of code:
staticFileLocation("/public");
When I type correct login and password I find in the network view in Chrome that I have GET request with status 200, OK, to http://localhost:4567/index.html. However, the browser does nothing and does not redirect me to that page. Can you tell me what I am doing wrong?
EDIT:
Here's javascript code that handles log in on the client side:
app.controller('LoginUserCtrl', function($scope, $http) {
$scope.loginUser = {};
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'http://localhost:4567/users/login',
data : $scope.loginUser,
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function() {
console.log("User logged successfully");
console.log($scope.loginUser);
}).error(function() {
console.log("Unknown error while logging user");
});
};
});
What's wrong is that you're redirecting to an HTML page in a post endpoint that's supposed to return Json data. You have to return a single json if authentication succeeded or failed, like {"auth": "OK"} or {"auth": "NOK"}, and decide where to redirect to from Javascript based in it's information.
It's because res.redirect will send a redirect http header(HTTP status values 301, 302, 303 and 307) to the browser,
but the browser only can redirect in get, NOT work in post or put or delete (Tested in chrome. Notice that a redirect request was sent by browser, but the page just not change...).
See:
http://www.alanflavell.org.uk/www/post-redirect.html

Resources