简体   繁体   English

使用 Nginx-ingress 时为 502,Docker Desktop + Kube.netes、Skaffold 和 Express JS

[英]502 when using Nginx-ingress, Docker Desktop + Kubernetes, Skaffold and Express JS

I am working on a project where I am using Ubuntu 22.04, Docker Desktop, Kube.netes 1.25.2, skaffold v2.0.3, NGINX Ingress Controller , express.js w/ Typescript. I am building out an auth service and when I run skaffold dev it all builds fine and my auth service is created, pods are created correctly and it even works fine and returns proper error messageing in postman.我正在开发一个项目,我正在使用 Ubuntu 22.04、Docker Desktop、Kube.netes 1.25.2、skaffold NGINX Ingress Controller 、express.js w/ 883622367 I1 am0588。 skaffold dev一切都构建良好,我的身份验证服务已创建,pod 已正确创建,它甚至可以正常工作并在 postman 中返回正确的错误消息。

I have began creating an error handling middleware function in express and want to use it as application mw to be able to return errors in a standard format.我已经开始在 express 中创建错误处理中间件 function 并希望将其用作应用程序 mw 以便能够以标准格式返回错误。 The issue comes when I try to throw new Error() in one of my files signup.ts .当我尝试在我的文件signup.ts之一中throw new Error()时,问题就来了。

In this file, if there is an error and I hit the endpoint in postman I get the correct json error when using res.status(400).send({message: "Something went wrong"}) .在此文件中,如果出现错误并且我在 postman 中命中了端点,则在使用res.status(400).send({message: "Something went wrong"})时会得到正确的 json 错误。 But as soon as I change the res.status() to throw new Error() which should be caught and returned by the mw, postman then throws a 502 coming from nginx.但是,一旦我将res.status()更改为throw new Error() ,它应该被 mw 捕获并返回,postman 就会抛出来自 nginx 的 502。

package.json package.json

{
  "name": "auth",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "ts-node-dev --watch src src/index.ts"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/express": "^4.17.15",
    "express": "^4.18.2",
    "express-validator": "^6.14.2",
    "nodemon": "^2.0.20",
    "ts-node-dev": "^2.0.0",
    "typescript": "^4.9.4"
  }
}

index.ts索引.ts

import express from 'express';
import signupRouter from './routes/signup';
import { errorHandler } from './middlewares/error-handler';

const app = express();
app.use(express.json());

// Middlewares
app.use(errorHandler);

// Use imported route handler
app.use(signupRouter);

app.listen(3000, () => console.log('Auth service listening on port 3000'));

signup.ts注册.ts

import express, { Request, Response } from 'express';
import { body, validationResult } from 'express-validator';

const signUpRouter = express.Router();

signUpRouter.post(
  '/api/users/signup',
  [
    body('email').isEmail().withMessage('Email must be valid'),
    body('password')
      .trim()
      .isLength({ min: 6, max: 20 })
      .withMessage('Password must be between 6 and 20 chars'),
  ],
  async (req: Request, res: Response) => {
    // May contain errors
    const errors = validationResult(req);

    // Causes 502 to return in response
    if (!errors.isEmpty()) throw new Error('Invalid email or password');

    // This line works properly in postman (no 502) when uncommented
    // if (!errors.isEmpty()) return res.send('Whoops, error happened')

    res.send({});
  }
);

export default signUpRouter;

errorHandler.ts errorHandler.ts文件

import { Request, Response, NextFunction } from 'express';

export const errorHandler = (
  err: Error,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  console.log('hiii'); // Never see this logged out

  res.status(400).json({
    message: err.message,
  });
};

auth-depl.yaml auth-depl.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: auth-depl
spec:
  replicas: 1
  # Step 1/2: Tell deployment how to find pods to create
  selector:
    matchLabels:
      app: auth
  # How to create each pod
  template:
    metadata:
      labels:
        app: auth
    spec:
      containers:
        - name: auth
          image: cookieman/auth
---
# Kubernates service to go with above pod
apiVersion: v1
kind: Service
metadata:
  name: auth-srv
spec:
  selector:
    # Find all pods with label of app:auth
    app: auth
  ports:
    - name: auth
      protocol: TCP
      port: 3000
      targetPort: 3000

ingress-srv.yaml入口-srv.yaml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress-service
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: 'true'
spec:
  rules:
    - host: tickethub.io
      http:
        paths:
          - path: /api/users/?(.*)
            pathType: Prefix
            backend:
              service:
                name: auth-srv
                port:
                  number: 3000

skaffold.yaml支架.yaml

apiVersion: skaffold/v2alpha3
kind: Config
deploy:
  kubectl:
    manifests:
      - ./infra/k8s/*
build:
  local:
    push: true
  artifacts:
    - image: cookieman/auth
      context: auth
      docker:
        dockerfile: Dockerfile
      sync:
        manual:
          # HMR for any js file then applied to k8s pod
          - src: 'src/**/*.ts'
            # Rebuild entire img if other non src/.ys file is changed
            dest: .

In my /etc/hosts file I have this line 127.0.0.1 tickethub.io .在我的/etc/hosts文件中,我有这一行127.0.0.1 tickethub.io

When sending the errored request I see this in the cli发送错误的请求时,我在 cli 中看到了这个

[auth] > auth@1.0.0 start
[auth] > ts-node-dev --watch src src/index.ts
[auth] 
[auth] [INFO] 23:36:56 ts-node-dev ver. 2.0.0 (using ts-node ver. 10.9.1, typescript ver. 4.9.4)
[auth] Auth service listening on port 3000
[auth] Error: Invalid email or password
[auth]     at /app/src/routes/signup.ts:20:34
[auth]     at Generator.next (<anonymous>)
[auth]     at /app/src/routes/signup.ts:8:71
[auth]     at new Promise (<anonymous>)
[auth]     at __awaiter (/app/src/routes/signup.ts:4:12)
[auth]     at /app/src/routes/signup.ts:15:41
[auth]     at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
[auth]     at next (/app/node_modules/express/lib/router/route.js:144:13)
[auth]     at middleware (/app/node_modules/express-validator/src/middlewares/check.js:16:13)
[auth]     at processTicksAndRejections (node:internal/process/task_queues:95:5)
[auth] [ERROR] 23:37:52 Error: Invalid email or password

I am not sure if this is an issue with express middleware, kube.netes, the nginx ingress controller etc...我不确定这是否是 express 中间件、kube.netes、nginx 入口 controller 等的问题...

Any advice?有什么建议吗?

Thank you.谢谢你。

Answer to my own question:回答我自己的问题:

This has nothing to do with being on Ubuntu. This has to do with a missing dependency for express validation when using typescript.这与使用 Ubuntu 无关。这与使用 typescript 时缺少对快速验证的依赖有关。

Answer:回答:

  1. Install this:安装这个:

npm install express-async-errors

  1. And then imported this into my error-hanlder.ts file.然后将其导入到我的error-hanlder.ts文件中。

import 'express-async-errors';导入“快速异步错误”;

  1. Make sure your error handling middleware comes after your route handlers in index.ts .确保您的错误处理中间件出现在index.ts中的路由处理程序之后。
// Use imported route handler
app.use(signupRouter);

// Middlewares (must come after route handlers)
app.use(errorHandler);

Hope this helps someone else.希望这可以帮助别人。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 mongoose 时出现 Typescript 错误(在 kubernetes 集群和支架内运行) - Typescript error when working with mongoose ( running inside kubernetes cluster and skaffold ) 使用TypeScript时是否应将Node.js / Express路由器包装在一个类中? - Should Node.js/Express Routers Be Wrapped in a Class When Using TypeScript? 使用Node.js和Express进行发布时的请求正文为空或未定义 - Request body when POSTing using Node.js and Express is empty or undefined 使用 express 时找不到模块 - Modules not found when using express 在我的 windows 主机文件中添加 LB IP 后,无法连接在浏览器上使用 ingress-nginx 生成的 Google Cloud Load Balancer - Not able to connect the Google Cloud Load Balancer generated using ingress-nginx on Browser after adding the LB IP in my windows hosts file 在 Express.js 中使用 Firebase 作为身份验证中间件 - Using Firebase as an Authenticating Middleware in Express.js express js 使用 mongoose 获取数据 - express js fetch data using mongoose 在express js模型中将js转换为打字稿时打字稿错误 - Typescript error when converting js to typescript in express js model 在 nextjs typescript 中收到“请求失败,状态码为 502 nginx - Receive "Request failed with status code 502 nginx in nextjs typescript 使用Socket.io-client,Node JS express和Webpack时,浏览器出现“ require not defined”错误 - When using Socket.io-client, Node JS express, and Webpack I am getting “require is not defined” error in the browser
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM