0

I'm trying to create a NodeJs Proxy, the request works fine for "GET" requests, tho it fails when I try the same but with "Post"/"Delete" Requests.

I am not sure to wether is it related to frontend or to backend:(

Would you have any idea of how to fix it?

const bodyParser = require('body-parser');
const express = require('express');
const morgan = require("morgan");
const { createProxyMiddleware } = require('http-proxy-middleware');

const jsonParser = bodyParser.json()
const app = express();
const PORT = 3003;
const HOST = "localhost";
const API_SERVICE_URL = "http://127.0.0.1:3333";

app.use(morgan('dev'));
app.use(bodyParser.json());

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    next();
});

// Proxy endpoints
app.use('/api', createProxyMiddleware({
    target: API_SERVICE_URL,
    changeOrigin: true,
    pathRewrite: {
        [`^/api`]: '',
    },
}));

// Start the Proxy
app.listen(PORT, HOST, () => {
    console.log(`Starting Proxy at ${HOST}:${PORT}`);
});

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ServiceService {

  constructor(private httpClient: HttpClient) {
  }

  public createNewUser(bodyParams: any): Observable<any> {
    return this.httpClient.post('http://localhost:3003/api/register', bodyParams);
  }
  public getTable(): Observable<any> {
    return this.httpClient.get('http://localhost:3003/api/table');
  }
  public deleteUser(username: string): Observable<any> {
    return this.httpClient.delete(`http://localhost:3003/api/delete/${username}`);
  }
}

enter image description here

enter image description here

Victoria
  • 165
  • 1
  • 12

1 Answers1

3

I've had this problem before but in my case the body parser that I was using was formidable instead of body-parser however I believe the problem is the same.

The main problem is that most express body parser middlewares will somehow modify the HTTP POST body. This means that by the time the proxy middleware gets your request the request will be mangled and corrupted which will cause the proxy request to fail.

The fix is to simply remove the body parser:

// Comment or better yet, delete the following line:
// app.use(bodyParser.json()); 

Once you do this you will find the proxy middleware working again for POST and DELETE requests.

If you need a body parser for a route install it just for that route. Installing it in the app is what breaks the proxy middleware:

// If you need a body parser:

app.post('/hello', bodyParser.json(), (req, res) => {
    // body parser is enabled only for this endpoint
});

// Or you can install it for entire routes:

let router = express.Router();

router.use(bodyParser.json());
router.post('/hello', (req,res) => {
    // body parser is enabled here
});

app.use('/with-parser',router);
slebetman
  • 109,858
  • 19
  • 140
  • 171