快递.js开机自检空要求正文

Express.js POST empty req.body

本文关键字:正文 js 开机自检 快递      更新时间:2023-09-26

无法通过简单的搜索解决此问题。如果有人能说得更清楚吗?

在客户端中,我尝试将对象附加到xhr.send(obj)。目前试图附加到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) 
}

在后端,我试图以这种方式获取 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()
})

不知道为什么,但每次我只打印出空对象。我已经检查了几次前端发送对象。

感谢任何帮助。

您可以尝试添加:

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

像这个快递(身体解析器)理解它必须解析传入的数据。