dougmoscrop / serverless-http

Use your existing middleware framework (e.g. Express, Koa) in AWS Lambda 🎉
Other
1.72k stars 166 forks source link

Missing Request body both Koa and Express #56

Closed Tan-nn closed 5 years ago

Tan-nn commented 6 years ago

I'm print all ctx but can not find body

serverless:

// index.js

const serverless = require('serverless-http');
var bodyParser = require('koa-bodyparser');
const AWS = require('aws-sdk');
const Router = require('koa-router');
var router = new Router();

const Koa = require('koa');
const app = new Koa();

// register your middleware as normal
app.use(bodyParser());
app
  .use(router.routes())
  .use(router.allowedMethods());

router
  .post('/test', async (ctx, next) => {  
    ctx.body = [{"name": 1, userId: "099999"}, ctx];
  })

module.exports.handler = serverless(app);

request body: {"userId": 123} but ctx:

 [
  {
    "name": 1,
    "userId": "099999"
  },
  {
    "request": {
      "method": "POST",
      "url": "/test",
      "header": {
        "content-length": 10,
        "x-request-id": "577c76fd-bb37-11e8-8e29-9757c42b128b"
      }
    },
    "response": {
      "status": 200,
      "message": "OK",
      "header": {
        "content-type": "application/json; charset=utf-8"
      }
    },
    "app": {
      "subdomainOffset": 2,
      "proxy": false,
      "env": "development"
    },
    "originalUrl": "/test",
    "req": "<original node req>",
    "res": "<original node res>",
    "socket": "<original node socket>"
  }
]

p/s: using LAMBDA_PROXY

dougmoscrop commented 5 years ago

The request header doesn't appear to specify a content-type? I think bodyparser is probably causing it. What happens if you remove bodyParser? do you see the body as a string?

Tan-nn commented 5 years ago

Hi @dougmoscrop Thanks for your reply. I have rem // app.use(bodyParser());, but got same result Note: Nodejs8.10

I write some dummy code and testing with api-gateway, it can response body as my request

function respBuilder(statusCode = 200, body = '') {
    return  {
        statusCode,
        body: JSON.stringify(body)
    };
}
exports.handler = async (event) => {
    if (!event.body)  {
        return respBuilder(400, "Bad request nha may");
    }
    // TODO implement
    return respBuilder(200, event.body)
};
roylee0704 commented 5 years ago

Having the same issue with express.js too.

roylee0704 commented 5 years ago

Found the culprit, if you use express.js >= v4, you have to app.use(require('body-parser').json()) to parse request body.

Taken from the following resource:

dougmoscrop commented 5 years ago

yeah there are numerous tests, and deployed apps, that are using body-parsing of json, I'm pretty sure this works unless you don't specify a content-type header (which is how it always works)