Mike Hardman
Mike Hardman

Reputation: 31

Nodejs proxy not streaming post data

I have a polymer website that is currently hosted under openresty/nginx. I am trying to migrate it to use nodejs express, in order to use passportjs for authentication (SAML)

I have configured a http-express-proxy to handle my api calls (/api/webapi/*). This proxy adds an bearer token to the request in order to authenticate. The API is am ASP.net restfull web service.

Most calls work except for my vaadin-upload requests. Where I get an 'Unexpected end of MIME multipart stream' error.

Proxy Config

const url = require('url');
const exproxy = require('express-http-proxy');

// Adds user authorization token from passport to request
var addAuthTokenMiddleware = function (req, res, next) {
    if (req.session && req.isAuthenticated()) {
        req.headers['Authorization'] = 'Bearer ' + req.user.token;
        next();
    } else {
       req.abort();
    }
};

function isLoggedIn(req, res, next) {
    // if user is authenticated in the session, carry on
    if (req.session && req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.redirect('/login');
};

// New hostname+path as specified by question:
const apiProxy = exproxy('http://127.0.0.1', {
    forwardPath: req => url.parse(req.originalUrl).path.replace("/api/webapi/",'/api/DataAccess.svc/api/v1/'),
    parseReqBody: false,
    preserveHostHdr: true
});


module.exports = function(app, passport) {
    app.use ('/api/webapi/*', isLoggedIn, addAuthTokenMiddleware, apiProxy);
    console.log(' Proxy Loaded');

}

Any help would be much appreciated

Thanks Mike

Upvotes: 1

Views: 1551

Answers (1)

Mike Hardman
Mike Hardman

Reputation: 31

I used http-proxy-middleware instead to alleviate the problem.

var hpmproxy = require('http-proxy-middleware');
function restream(proxyReq, req) {
    if (!isEmpty(req.body)) {

        var bodyData = JSON.stringify(req.body);
        proxyReq.setHeader('Content-Type', 'application/json');
        proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
        proxyReq.write(bodyData);
    }
};
var options = {
    target: config.webApiHost,

    changeOrigin: true, // needed for virtual hosted sites
    pathRewrite: {
        '^/api/webapi': config.webApiPath
    },
    secure: !config.selfSigned,
    onProxyReq: restream
};
var hpmApiProxy = hpmproxy(options);
app.use('/api/webapi/', isLoggedIn, addAuthTokenMiddleware, hpmApiProxy);

Upvotes: 1

Related Questions