2016-04-25 138 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