POSTMAN not sending anything in the body in POST requests

Mr.*_*r.P 7 http-post postman

I am trying to test the /login API via POSTMAN (via FE it works fine) but it doesn't show anything in the body part even though I am sending body data.

在此输入图像描述

but when printing the request from the BE, the body is empty...

  ....
  body: {},
  ....
Run Code Online (Sandbox Code Playgroud)

unlike when using FE:

  ....
  body: {data: { username: 'admin', password: 'admin' }},
  ....
Run Code Online (Sandbox Code Playgroud)

Any idea what's going on? If anything else is needed to be provided - pls let me know

I know it's going through because the server responds with 500 and the message

TypeError: Cannot read property 'username' of undefined

The weird part is, that the data I am sending, are nowhere to be found in the request object at all :(

EDIT:

This is how I call it from the FE:

return axios.post('login', { data: user })

and the user is:

user: {
  username: 'admin',
  password: 'admin'
}
Run Code Online (Sandbox Code Playgroud)

So the format should be right

data: { 
    username: 'admin', 
    password: 'admin'
}
Run Code Online (Sandbox Code Playgroud)

Because that's how I access it on the BE side

req.body.data.username

EDIT2:

The ultra-super-rare-weird part is, that JEST is working fine :)

const creds = {
      data: {
            username: 'admin',
            password: 'admin'
            }
    }

    return request(app)
      .post("/api/v1/login")
      .send(creds)
      .expect(200)
      .then(res => {
        expect(res.body).toMatchSnapshot()
      })
Run Code Online (Sandbox Code Playgroud)

and this test passes .... f**k me guys.. what's going on?

Seh*_*eed 13

如果您正在使用 Express 服务器,请在路由之前初始化 Express 应用程序后立即尝试在服务器中解析您的正文

const app = express();
app.use(express.json());
Run Code Online (Sandbox Code Playgroud)


小智 12

正文的语法看起来像 JSON,但您已将正文的类型指定为“原始文本”。这会将请求的 Content-type 标头设置为“text/plain”,这可能会导致您的后端无法实际读取正文(因为它需要 JSON 对象)。

只需从“文本”切换到“JSON”,将当前正文括在大括号中(以便实际上发送带有数据属性集的单个 JSON 对象),然后尝试再次发送请求。这次内容类型标头将正确设置为“application/json”,您的后端将成功读取数据。


小智 6

在Postman的请求头配置中添加以下参数:

 Content-Type: application/json
 Content-Length
Run Code Online (Sandbox Code Playgroud)

Content-Length的值是Postman在发送请求时自动计算的。这两个值都用于识别请求正文的媒体类型并准确解析它。当丢失时,主体可能会被完全忽略(取决于服务器)。