WebSocket Connection Issues with Localhost and Proxy Configuration in Angular

Discussão em 'Angular' iniciado por Reginna, Outubro 18, 2024.

  1. Reginna

    Reginna Guest

    I use proxy.config to set headers for the Angular project.

    The project is supposed to use WebSocket, but the WebSocket cannot connect when using localhost.

    The API calls (GET, POST, PUT, DELETE) work fine with localhost, but WebSocket cannot connect. Otherwise, the website functions normally.

    The WebSocket connects when the origin is "https://com-name.example-dev.net", but if I use localhost, it doesn't work.

    Env settings:

    // .env file
    // dev
    PROXY_TARGET=https://api.example-dev.net
    HEADER_ORIGIN="https://com-name.example-dev.net"
    WEBSOCKET_TARGET=wss://api.example-dev.net


    Proxy settings:

    // proxy.config.js
    const path = require('path');
    const dotenv = require('dotenv');
    const { log } = require('console');

    dotenv.config({ path: path.join(__dirname, `./.env`) });

    const PROXY_CONFIG = {
    '/api/**': {
    target: process.env.PROXY_TARGET,
    changeOrigin: true,
    logLevel: 'debug',
    pathRewrite: {},
    secure: false,
    ws: true,
    headers: { origin: process.env.HEADER_ORIGIN || 'localhost:80' },
    cookieDomainRewrite: { '*': 'localhost' }
    },
    };

    module.exports = PROXY_CONFIG;


    I start the project with the start script.

    // package.json
    {
    "script": {
    "start": "run-p \"start:nx {1} --open --port {2} --host 0.0.0.0\" --"
    }
    }


    Am I missing some settings?


    Additionally, I tried changing the host file settings on my computer (C:\Windows\System32\drivers\etc\hosts):

    // added this line
    127.0.0.1 com-name.example-dev.net


    When I open http://com-name.example-dev.net, it shows the local project and the WebSocket connects successfully.

    However, using this method requires adding a new host entry every time I develop and removing it after I finish, which is inconvenient. Is there a better way to solve this?

    Should I ask the WebSocket developer to add Access-Control-Allow-Origin: http://localhost:pORT?

    Continue reading...

Compartilhe esta Página