Express.js - Route called twice because of CORS

Discussão em 'Angular' iniciado por Raphael, Janeiro 9, 2025.

  1. Raphael

    Raphael Guest

    I have the following Node.js code:

    import express from 'express';
    import cors from 'cors';

    const app = express();

    // Enable CORS
    const origin = [];

    origin.push(
    /http:\/\/localhost:.*/,
    /https:\/\/localhost:.*/,
    /http:\/\/127\.0\.0\.1:.*/,
    /https:\/\/127\.0\.0\.1:.*/
    );

    app.use(
    cors({
    origin,
    credentials: true
    })
    );

    app.put('/', (req, res, next) => {
    console.log('PUT REQUEST');
    res.status(200).json({});
    });

    app.listen(5000, () => {
    console.log('Server is running on port 5000');
    });


    When I call the route from Angular:

    constructor(private http: HttpClient) {
    this.http.put('http://localhost:5000', {}).subscribe();
    }


    I get this in my Node.js console:

    PUT REQUEST
    PUT REQUEST


    The route is called twice when CORS is enabled. It doesn't happen when CORS is disabled:

    // const origin = [];

    // origin.push(
    // /http:\/\/localhost:.*/,
    // /https:\/\/localhost:.*/,
    // /http:\/\/127\.0\.0\.1:.*/,
    // /https:\/\/127\.0\.0\.1:.*/
    // );

    // app.use(
    // cors({
    // origin,
    // credentials: true
    // })
    // );


    The output without CORS is:

    PUT REQUEST


    Does somebody have an explanation/solution?

    Note: I also tried to call the route from a React front and it runs properly. It looks like an issue with CORS and Angular.

    Continue reading...

Compartilhe esta Página