Proxy Express requests to laravel API

2019-08-07 15:12发布

I'm converting my application to a React Universal app. I would like to proxy all "/api/*" requests from the express server to my laravel api. I found a great boilerplate to help build the server side portion of the react app but I can't get it to proxy my requests using http-proxy.

If I want to proxy "/api/users" to "http://laravel.app/api/users", what do I need to change in my setup?

// NODE
import http from 'http';
import path from 'path';

// EXPRESS
import express from 'express';
import favicon from 'serve-favicon';
import httpProxy from 'http-proxy';

const proxy = httpProxy.createProxyServer();

// Profile dev or production
let profile = process.env.DEV ? 'dev' : 'prod',
    publicPath = profile === 'dev' ? 'build' : 'dist';

let app = express();

app.set('port', process.env.PORT || 3000);
app.use(express.static(publicPath));
app.use(favicon(path.join(__dirname, '../app/images/favicon.ico')));

//
// Register middlewares
// --------------------

// renderer
let renderer = require('./routes/renderer');

//
// Configure middlewares
// --------------------
renderer.init(profile);

//
// Activate middlewares
// --------------------
//
app.use('/api/*', (req, res) => {
  proxy.web(req, res, { target: 'http://laravel.app:80' });
});
app.use(renderer.render);

http.createServer(app).listen(app.get('port'), () => {
  console.log('Express server listening on port ' + app.get('port'));
});

//
// check if HMR is enabled
// --------------------
if(module.hot) {
  // accept update of dependency
  module.hot.accept(['./routes/api', './routes/renderer'], () => {
    app.use('/api/*', (req, res) => {
      proxy.web(req, res, { target: 'http://laravel.app:80' });
    });
    renderer = require('./routes/renderer');
    renderer.init('dev');
  });
}

0条回答
登录 后发表回答