Proxy with express.js

前端 未结 9 1512
别那么骄傲
别那么骄傲 2020-11-28 00:29

To avoid same-domain AJAX issues, I want my node.js web server to forward all requests from URL /api/BLABLA to another server, for example other_domain.co

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 01:17

    First install express and http-proxy-middleware

    npm install express http-proxy-middleware --save
    

    Then in your server.js

    const express = require('express');
    const proxy = require('http-proxy-middleware');
    
    const app = express();
    app.use(express.static('client'));
    
    // Add middleware for http proxying 
    const apiProxy = proxy('/api', { target: 'http://localhost:8080' });
    app.use('/api', apiProxy);
    
    // Render your site
    const renderIndex = (req, res) => {
      res.sendFile(path.resolve(__dirname, 'client/index.html'));
    }
    app.get('/*', renderIndex);
    
    app.listen(3000, () => {
      console.log('Listening on: http://localhost:3000');
    });
    

    In this example we serve the site on port 3000, but when a request end with /api we redirect it to localhost:8080.

    http://localhost:3000/api/login redirect to http://localhost:8080/api/login

提交回复
热议问题