question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

undefined in a HTTP POST body

See original GitHub issue

I wrote a handler like this. When I use form post or Postman’s post, it gets an empty object. But I use supertest to test it, it seems OK, and get the right body object.

request.body is always undefined.

    @Post("/")
    async saveOne(@Body() data) { //data is {} if not in test
        return await this.todoService.save(data);
    }

test code: PASS

"use strict";
describe("Todo测试", ()=> {
    const expect = require("chai").expect;
    const supertest = require("supertest");
    const request = supertest.agent(`http://localhost:${process.env.LEANCLOUD_APP_PORT}`);

    it("写入对象", (done)=> {
        request.post("/todos").send({"content": `测试数据 - ${new Date()}`}).expect(200).end((e, res)=> {
            expect(res.body).to.be.an("object", "返回对象");
            done();
        });
    });
});

Chrome’s POST form submit: FAILED

curl 'http://localhost:3000/todos' -H 'Origin: http://localhost:3000' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: zh-CN,zh;q=0.8' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36' -H 'Content-Type: application/x-www-form-urlencoded' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H 'Cache-Control: max-age=0' -H 'Referer: http://localhost:3000/' -H 'Connection: keep-alive' -H 'DNT: 1' --data 'content=test' --compressed

Postman’s curl: FAILED

curl -X POST -H "Cache-Control: no-cache" -H "Postman-Token: e06e03e8-6009-28f6-59cc-0cc72ac6dfbc" -H "Content-Type: application/x-www-form-urlencoded" -d 'content=value to be save&ignore=value to be ignore' "http://localhost:3000/todos"

p.s. just ignore those Chinese characters,there’re nothing to do with this issue, consider them just strings

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:1
  • Comments:8 (7 by maintainers)

github_iconTop GitHub Comments

1reaction
Dilukacommented, Aug 16, 2016

but I still have a question

when I use json params to post, how can I do pre-process in a middleware. at the beginning, the json params successfully inject into the method params, but I can’t get it from req.body

and I response json, but get any kind of params by middlewares translating into json to handle. which decorator shall I use, @Controller or @JsonController ? Now I use @JsonController and body-parser. Is this right?

1reaction
pleerockcommented, Aug 16, 2016

I tried, it’s the same. And the normal html form doesn’t json, it’s not work too. Besides, the request body is always undefined, how can I use middleware to deal with?

if you are working with json, you should always specify json content headers. btw are you using @JsonController or @Controller. Because if you are working NOT WITH JSON (forms are not working with json) you should use @Controller, not @JsonController.

export const app: Express.Application = createExpressServer({ controllerDirs: [__dirname + “/controller//*.controller.js"], middlewareDirs: [__dirname + "/middleware//.middleware.js"], interceptorDirs: [dirname + "/interceptor//.interceptor.js”] }); app.use(json()); app.use(urlencoded({extended: true}));

You are doing it wrong. createExpressServer creates and bootstraps express server. You probably should do you logic before it bootstrap the app. To do that you need to create your own express server and use useExpressServer instead. Something like this:

const app = express();
app.use(json());
app.use(urlencoded({extended: true}));
useExpressServer(app, {
    controllerDirs: [__dirname + "/controller/**/*.controller.js"],
    middlewareDirs: [__dirname + "/middleware/**/*.middleware.js"],
    interceptorDirs: [__dirname + "/interceptor/**/*.interceptor.js"]
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

Undefined body from post request in nodejs - Stack Overflow
I created the API in node js and in the POST method getting the body as undefined. How can I get the value...
Read more >
All values undefined in POST requests - Help - Postman
Hello all, I'm brand new to APIs and Postman. I can't seem to get the data from my POST request to my console....
Read more >
req.body undefined in POST request - Google Groups
I seem to have a problem with req.body being "undefined" when using a. POST request. Im using expresso to do the POST: --...
Read more >
Very simple test script for handling POST requests with NodeJS
I have already installed the body-parser. This is the script: var express = require('express'); var http = require('http'); var app = express(); ...
Read more >
request.body is undefined in node js - You.com
1 Answer. Looks like you are hooking up your routes before any parsing middleware, which would explain why you don't get any body...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found