[英]Express.js POST empty req.body
簡單搜索無法解決此問題。 如果有人能說得更清楚?
在客戶端中,我嘗試將對象附加到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");
像這個表述(正文解析器)理解的那樣,它必須解析傳入的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.