4

我正在尝试通过无服务器 Lambda 代理外部 API。尝试以下代码示例:http://localhost:3000/users/1返回 200 但正文为空。我必须忽略一些东西,因为http://localhost:3000/users/11返回 404(如预期的那样)。

index.js

'use strict';
const serverless = require('serverless-http');
const express = require('express');
const {
  createProxyMiddleware
} = require('http-proxy-middleware');

const app = express();

const jsonPlaceholderProxy = createProxyMiddleware({
  target: 'http://jsonplaceholder.typicode.com',
  changeOrigin: true,
  logLevel: 'debug'
});

app.use('/users', jsonPlaceholderProxy);

app.get('/', (req, res) => {
  res.json({
    msg: 'Hello from Serverless!'
  })
})

const handler = serverless(app);
module.exports.handler = async (event, context) => {
  try {
    const result = await handler(event, context);
    return result;
  } catch (error) {
    return error;
  }
};

无服务器.yml

service: sls-proxy-test

provider:
  name: aws
  runtime: nodejs12.x

plugins:
  - serverless-offline

functions:
  app:
    handler: index.handler
    events:
      - http:
          method: ANY
          path: /
      - http: "ANY {proxy+}"

包.json

{
  "name": "proxy",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "sls": "sls",
    "offline": "sls offline start"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "4.17.1",
    "http-proxy-middleware": "1.0.1",
    "serverless-http": "2.3.2"
  },
  "devDependencies": {
    "serverless": "1.65.0",
    "serverless-offline": "5.12.1"
  }
}
4

2 回答 2

1

尝试从内部侦听器transfer-encoding的响应中删除标头onProxyRescreateProxyMiddleware

const jsonPlaceholderProxy = createProxyMiddleware({
  onProxyRes: function (proxyRes, req, res) { // listener on response
    delete proxyRes.headers['transfer-encoding']; // remove header from response
  },
  // remaining code

于 2021-03-26T22:07:37.200 回答
0

我有同样的问题,但添加下面的 onProxyRes 选项解决了它

  onProxyRes(proxyRes, req, res) {
    const bodyChunks = [];
    proxyRes.on('data', (chunk) => {
      bodyChunks.push(chunk);
    });
    proxyRes.on('end', () => {
      const body = Buffer.concat(bodyChunks);
      res.status(proxyRes.statusCode);
      Object.keys(proxyRes.headers).forEach((key) => {
        res.append(key, proxyRes.headers[key]);
      });
      res.send(body);
      res.end();
    });
  }
于 2020-07-02T18:28:56.867 回答