简体   繁体   English

Express.js POST空的req.body

[英]Express.js POST empty req.body

Cannot resolve this issue by simple search. 简单搜索无法解决此问题。 If anyone can make that more clear? 如果有人能说得更清楚?

In client I've tried attach object to xhr.send(obj). 在客户端中,我尝试将对象附加到xhr.send(obj)。 At the moment trying to append to formData object, result the same while... Client code: 此刻试图追加到formData对象,结果相同...客户代码:

var xhr = new XMLHttpRequest()    
xhr.open("post", "/api/test", true)

var formData = new FormData()
formData.append("hi", "hello")

xhr.send(formData)

xhr.onreadystatechange = function() {
  if (this.readyState != 4)
    return
  if (this.status != 200) return console.error(this.status + this.statusText)
  else console.log(this.responseText) 
}

And on back-end I am trying to get req.body this way: 在后端,我试图通过这种方式获取req.body:

const express = require('express'),
    app = express(),
    http = require('http'),
    path = require('path'),
    bodyParser = require('body-parser')    

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

app.use(express.static('public'))

app.get('/', function(req, res) {
  res.sendFile(path.resolve("/public/index.html"))
})

app.post('/api/test', (req, res) => {
  console.log(req.body)
  res.end()
})

Don't see why, but each time I get printed out only empty objects. 不知道为什么,但是每次我打印出的都是空的对象。 I've cheked several times front end sends objects. 我已经多次咀嚼前端发送对象。

Appreciate any help. 感谢任何帮助。

You can try to add : 您可以尝试添加:

//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Like this express (body parser) understand it have to parse the incoming data. 像这个表述(正文解析器)理解的那样,它必须解析传入的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM