Proxy with express.js

前端 未结 9 1510
别那么骄傲
别那么骄傲 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:20

    You want to use http.request to create a similar request to the remote API and return its response.

    Something like this:

    const http = require('http');
    // or use import http from 'http';
    
    
    /* your app config here */
    
    app.post('/api/BLABLA', (oreq, ores) => {
      const options = {
        // host to forward to
        host: 'www.google.com',
        // port to forward to
        port: 80,
        // path to forward to
        path: '/api/BLABLA',
        // request method
        method: 'POST',
        // headers to send
        headers: oreq.headers,
      };
    
      const creq = http
        .request(options, pres => {
          // set encoding
          pres.setEncoding('utf8');
    
          // set http status code based on proxied response
          ores.writeHead(pres.statusCode);
    
          // wait for data
          pres.on('data', chunk => {
            ores.write(chunk);
          });
    
          pres.on('close', () => {
            // closed, let's end client request as well
            ores.end();
          });
    
          pres.on('end', () => {
            // finished, let's finish client request as well
            ores.end();
          });
        })
        .on('error', e => {
          // we got an error
          console.log(e.message);
          try {
            // attempt to set error message and http status
            ores.writeHead(500);
            ores.write(e.message);
          } catch (e) {
            // ignore
          }
          ores.end();
        });
    
      creq.end();
    });
    

    Notice: I haven't really tried the above, so it might contain parse errors hopefully this will give you a hint as to how to get it to work.

提交回复
热议问题