2016-04-25 87 views
0

無法通過簡單搜索解決此問題。如果任何人都可以做得更清楚?Express.js POST空請求身份

在客戶端我已經嘗試附加對象到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() 
}) 

看不到爲什麼,但每次只打印出空物體。我已經多次嘗試前端發送對象。

感謝任何幫助。

回答

1

你可以嘗試添加:

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

像這種快遞(正文分析器)瞭解它要解析的輸入數據。

+0

很簡單=))非常感謝。我一直在玩像一個小時)) – Lazyexpert

+0

沒問題:)不客氣 – jaumard