Saturday, June 28, 2025

Angular: proxy.conf.json; React: vite proxy

Angular

angular.json
        "serve": {
          "options": {
            "ssl": true,
            "sslKey": "ssl/key.pem",
            "sslCert": "ssl/cert.pem",
            "proxyConfig": "proxy.conf.json"
          },
          "builder": "@angular/build:dev-server",
          "configurations": {
            "production": {
              "buildTarget": "react-analogous:build:production"
            },
            "development": {
              "buildTarget": "react-analogous:build:development"
            }
          },
          "defaultConfiguration": "development"
        },
proxy.conf.json
secure = false, just a self-signed certificate
{
  "/api": {
    "target": "https://localhost:7249",
    "secure": false,
    "changeOrigin": true,
    "logLevel": "debug"
  }
}

React

React's vite proxy
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'

import fs from 'fs';

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    https: {
      key: fs.readFileSync('localhost-key.pem') ,
      cert: fs.readFileSync('localhost.pem'),
    },
    port: 3000,
    proxy: {
      '/api': { // This is the prefix for requests you want to proxy
        target: 'https://localhost:7249', // The URL of your backend API
        changeOrigin: true, // Rewrites the origin header to match the target URL
        // rewrite: (path) => path.replace(/^\/api/, ''), // Optional: remove '/api' from the request path sent to the backend
        secure: false, // Optional: if your backend uses HTTPS but has a self-signed certificate
        // agent: new http.Agent(), // Optional: if using HTTPS with a specific agent
      },
    },
  },
})

No comments:

Post a Comment