ExpressJS routes not resolving - javascript

I have a small microservice written in typescript running in a kubernetes cluster on AKS.
I have ingress generated using Helm
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: test-service
labels:
app: test-service
chart: test-service-0.1.0
release: test-service
heritage: Tiller
annotations:
ingress.kubernetes.io/rewrite-target: /
kubernetes.io/ingress.class: nginx
kubernetes.io/tls-acme: "true"
spec:
tls:
- hosts:
- test.xyz
secretName: default-tls
rules:
- host: test.xyz
http:
paths:
- path: /payments
backend:
serviceName: test-service
servicePort: 4040
And the service
apiVersion: v1
kind: Service
metadata:
name: existing-bumblebee-payments-service
labels:
app: test-service
chart: test-service-0.1.0
release: existing-bumblebee
heritage: Tiller
spec:
type: ClusterIP
ports:
- port: 4040
targetPort: 4040
protocol: TCP
selector:
app: test-service
release: existing-bumblebee
And in my microservice
export class Server {
private registerRoutes() {
this.app.use("/cards", CardRouter);
this.app.use("/wallets", WalletRouter);
this.app.use("/preauth", PreauthRouter);
this.app.use("/charge", ChargeRouter);
}
}
The routers look like this;
import { Router } from "express";
// other imports
import { checkSchema, check } from "express-validator/check";
const router = Router();
router.get("/", CardController.index);
router.get("/:id", [
check("id")
.isUUID()
.withMessage("Invalid UUID")
], CardController.get);
router.delete("/:id", [
check("id")
.isUUID()
.withMessage("Invalid UUID")
], CardController.remove);
router.post("/", checkSchema(CardCreateRules), CardController.add);
export default router;
But accessing the service via https://test.xyz/payments/cards results in a 404 error from express
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /payments/cards</pre>
</body>
</html>
I can tell the response is from the express server cause it has custom response headers set by the server.
I'm really confused as to what is wrong, any help will be appreciated.

It does not work for you because your ingress just redirects request https://test.xyz/payments/cards to test-service without rewriting the path. So test service still becomes request "/payments/cards" and obviously can not handle them.
You can either reconfigure express application to support /payments/cards or do the path rewrite via ingess 'nginx.ingress.kubernetes.io/rewrite-target' annotation:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: test-service
labels:
app: test-service
chart: test-service-0.1.0
release: test-service
heritage: Tiller
annotations:
ingress.kubernetes.io/rewrite-target: /
kubernetes.io/ingress.class: nginx
kubernetes.io/tls-acme: "true"
nginx.ingress.kubernetes.io/rewrite-target: /payments
spec:
tls:
- hosts:
- test.xyz
secretName: default-tls
rules:
- host: test.xyz
http:
paths:
- path: /
backend:
serviceName: test-service
servicePort: 4040

Related

Changing Swagger Path URI to Server Name In Hapi-js Using Hapi-swagger

How Can Change SwaggerPath Dynamically to severname, Down I have Given Swagger Options and Sever
with Plugins.
/** ******************** swagger Options*********************** */ const swaggerOptions: HapiSwagger.RegisterOptions = { info: { title: 'Demo API', version: Pack.version, description, }, schemes: \['https', 'http'\], grouping: 'tags', sortEndpoints: 'ordered', documentationPath: "/api/v1/docs, basePath: "/api/v1", jsonPath:/api/v1/json, swaggerUIPath: /api/v1/swaggerUI`,
pathPrefixSize: '/api/v1/docs'.length,
payloadType: 'json',
securityDefinitions: {
jwt: {
type: 'apiKey',
name: 'Authorization',
in: 'header',
'x-keyPrefix': 'Bearer ',
},
},
security: [{ jwt: [] }],
// Without this, the Authorization headers are never sent, but with them they are!
};
//************************** HAPI SERVER ********************************//
const init = async () => {
/** ***********************Create a server************************ */
const server: any = Hapi.server({
port: 4040,
host: 'localhost',
routes: {
cors: true,
},
});
await server.register(Plugins);
await server.start();
};
init();
//\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* Plugins**********//
/** **Import Module*** \*/
import \* as Hapi from '#hapi/hapi';
import \* as Inert from '#hapi/inert';
import \* as Vision from '#hapi/vision';
import \* as HapiSwagger from 'hapi-swagger';
/\*\* \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* Import options \*\*\*\*\*\*\*\*\*\*\*\*\**/
import swaggerOptions from '../config/options/swaggerOptions';
import statusMonitor from '../config/options/statusMonitor';
/\*\* \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* Plugin \*\*\*\*\*\*\*\*\*\*\*\*\\*/
const plugins: Array\<Hapi.ServerRegisterPluginObject\<any\>\> = \[
{
plugin: Inert,
},
{
plugin: Vision,
},
{
plugin: HapiSwagger,
options: swaggerOptions,
},
];
/** ******************** Export All *********************** */.
export default plugins; `
I need to configure with https scheme with my server domain name how Can do that
i.e( for Example My server is running at Domain Name then my swagger is running in My server name But My server is running localhost So that My server Point out the localhost Not the Domain When Try run My swagger in server name )

Permanent redirect for www to non-www site using NextJs

I've built a website with Nextjs (using version 12.1.4). For SEO purposes I would like to make a permanent redirect for my www version of the site to my non-www. Normally this could easily be done with nginx or an .htaccess file with apache. However, static websites hosted on Digitalocean are not running apache or nginx so an .htaccess file won’t do. I've read that this should be possible using Nextjs redirects.
I've tried the following 3 redirects:
redirects: async () => [
{
source: '/:path*',
has: [
{
type: 'host',
value: 'www',
},
],
destination: '/:path*',
permanent: true,
},
],
---------------------------------------------------
redirects: async () => [
{
source: '/:path*/',
has: [
{
type: 'host',
value: 'www',
},
],
destination: '/:path*/',
permanent: true,
},
],
------------------------------------------------------
redirects: async () => [
{
source: '/:path*',
has: [{ type: 'host', value: 'https://www.cvtips.nl/' }],
destination: 'https://cvtips.nl/:path*',
permanent: true,
},
],
All of them don't seem to redirect to the non-www version. I don't know if it is relevant, but I do use trailingSlash: true in the config.
Next thing I tried is adding a middleware file. I both tried adding it at the root and calling it middleware.js and inside the pages folder calling it _middleware.js.
This is the code I use for the redirect:
--> https://github.com/vercel/next.js/discussions/33554
import { NextRequest, NextResponse } from 'next/server';
export function middleware(req: NextRequest) {
const host = req.headers.get('host');
const wwwRegex = /^www\./;
// This redirect will only take effect on a production website (on a non-localhost domain)
if (wwwRegex.test(host) && !req.headers.get('host').includes('localhost')) {
const newHost = host.replace(wwwRegex, '');
return NextResponse.redirect(`https://${newHost}${req.nextUrl.pathname}`, 301);
}
return NextResponse.next();
}
Also does not work at all... Doesn't do anything I believe.
How can I redirect a Nextjs website from www to non-www?

Routes from frontend shown as insecure in https website

I created a webpage using vue.js and on backend node.js.
When I access the main page ( https://example.test ) I got secure info on my browser, but once I go to other links ( https://example.test/dashboard ) I got an insecure connection.
"devServer": {
allowedHosts: ['example.test'],
host: "0.0.0.0",
port: 443,
server : {
type: "https",
options: {
key: fs.readFileSync('/usr/app/key.pem'),
cert: fs.readFileSync('/usr/app/cert.pem')
}},
hot: true
}
Is there any configuration that I'm missing in vue.config.js or I'm missing something in router/index.js?
Vue.use(VueRouter)
const routes = [
{
path: "/sign-in",
name: "signIn",
component: SignIn,
meta: {
requiresNotAuth: true
}
},
{
path: "/dashboard",
name: "dashboard",
component: Dashboard,
meta: {
requiresAuth: true
}
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
UPDATE
security in https://example.test:
Security in https://example.test/dashboard:

Adonis 5 + Vue "E_ROUTE_NOT_FOUND"

I'm doing an Adonis v5 app with Vue 2 as frontend.
My problem is, once I've build Vue frontend into public adonis folder. If I access to a speficic route writing it into the top browser searcher, I get the E_ROUTE_NOT_FOUND from Adonis.
I do think that adonis is trying to search the route into the router of the server and not into the Vue router. Althought adonis it's configured to use static files and the first frontend page works:
Vue router.js:
Vue.use(VueRouter);
const routes = [
{
path: "/",
redirect: { name: "acceso" },
},
{
path: "/acceso",
name: "acceso",
component: SignupView,
meta: { guestAllow: true },
}];
const router = new VueRouter({
mode: "history",
routes,
});
Adonis routes.ts (It shouldn't affect as the have a prefix:
Route.group(() => {
Route.group(() => {
Route.post("register", "AuthController.register");
Route.post("login", "AuthController.login");
}).prefix("auth");
Route.group(() => {
Route.get("logs", "LogsController.index");
}).middleware("auth:api");
}).prefix("/api");
Adonis static.ts:
import { AssetsConfig } from '#ioc:Adonis/Core/Static'
const staticConfig: AssetsConfig = {
enabled: true,
dotFiles: 'ignore',
etag: true,
lastModified: true,
maxAge: 0,
immutable: false,
}
If I write localhost:3333 on the browser I redirects to /access (Correct)
But if I refresh the page, or browse manually the same route, the error shows
Any idea of what could it be?
Thank you for your time.
After looking some other projects on internet, I've seen that if you use mode: "history" on vue-router it pops the error.
So I've tried to comment this line and now I can refresh the page without E_ROUTE_NOT_FOUND error.
Frontend Vue router.js:
const router = new Router({
//mode: "history",
routes,
});

Serve asset files in nginx using Kubernetes

I'm trying to deploy a pod to kubernetes using my node app and an nginx proxy server which should also serve my asset files.
I'm using two containers inside one pod for that. Below code runs the application correctly but asset files are not being served by nginx.
Below is my front-end-deployment.yaml files which takes care of creating the deployment for me. I'm wondering why nginx by this configurations doesn't not serve the static files?
apiVersion: v1
kind: ConfigMap
metadata:
name: mc3-nginx-conf
data:
nginx.conf: |
user nginx;
worker_processes 3;
error_log /var/log/nginx/error.log;
events {
worker_connections 10240;
}
http {
log_format main
'remote_addr:$remote_addr\t'
'time_local:$time_local\t'
'method:$request_method\t'
'uri:$request_uri\t'
'host:$host\t'
'status:$status\t'
'bytes_sent:$body_bytes_sent\t'
'referer:$http_referer\t'
'useragent:$http_user_agent\t'
'forwardedfor:$http_x_forwarded_for\t'
'request_time:$request_time';
access_log /var/log/nginx/access.log main;
upstream webapp {
server 127.0.0.1:3000;
}
server {
listen 80;
root /var/www/html;
location / {
proxy_pass http://webapp;
proxy_redirect off;
}
}
}
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend
spec:
replicas: 3
selector:
matchLabels:
component: web
template:
metadata:
labels:
component: web
spec:
volumes:
- name: nginx-proxy-config
configMap:
name: mc3-nginx-conf
- name: shared-data
emptyDir: {}
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
volumeMounts:
- name: nginx-proxy-config
mountPath: /etc/nginx/nginx.conf
subPath: nginx.conf
- name: shared-data
mountPath: /var/www/html
- name: frontend
image: sepehraliakbari/rtlnl-frontend:latest
volumeMounts:
- name: shared-data
mountPath: /var/www/html
lifecycle:
postStart:
exec:
command: ['/bin/sh', '-c', 'cp -r /app/build/client/. /var/www/html']
ports:
- containerPort: 3000

Categories