【问题标题】:NodeJs Proxy Issue forwarding POST/DELETE requestsNodeJs 代理问题转发 POST/DELETE 请求
【发布时间】:2021-02-26 14:41:44
【问题描述】:

我正在尝试创建 NodeJs 代理,该请求适用于“GET”请求,但当我尝试相同但使用“Post”/“Delete”请求时它会失败。

我不确定它是否与前端或后端有关:(

您知道如何解决它吗?

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}`);
  }
}

【问题讨论】:

    标签: node.js angular http nodejs-server


    【解决方案1】:

    我以前遇到过这个问题,但在我的情况下,我使用的正文解析器是 formidable 而不是 body-parser 但我相信问题是一样的。

    主要问题是大多数快速正文解析器中间件会以某种方式修改 HTTP POST 正文。这意味着当代理中间件收到您的请求时,请求将被破坏和损坏,这将导致代理请求失败。

    解决方法是简单地删除正文解析器:

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

    执行此操作后,您会发现代理中间件再次为 POST 和 DELETE 请求工作。

    如果您需要一个路由的正文解析器,请仅为该路由安装它。在应用程序中安装它会破坏代理中间件:

    // 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);
    

    【讨论】:

      猜你喜欢
      • 2011-06-24
      • 1970-01-01
      • 2017-01-11
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      相关资源
      最近更新 更多