2016-02-20 64 views
2

客戶端空的,這是我所發生的事情:要求身體總是在POST

function saveGrades() { 
    $.post("/savegrades", {classIndex: "classIndexId"}); } 

服務器端:

router.post('/savegrades', stormpath.loginRequired, function(req, res) { 
    console.log("Class index: " + req.body.classIndex); 
    console.log(req.body); 
    res.send(200); 
}); 

bodyParser設置如下:

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

無論我嘗試過什麼,req.body都是空的,並且沒有classIndex。我做錯了什麼?爲什麼數據沒有發佈到服務器?

編輯:對於鏈接的問題,我經歷了幾乎所有相關的答案,無法找到解決方案。看起來這些數據永遠不會被髮送到服務器。當我用調試器檢查它時,主體總是空的。

+0

http://stackoverflow.com/questions/5570747/jquery-posting-json –

+0

@發送AndreyPopov我無法用這個問題的答案來解決我的問題。 – iamtesla

+0

我會試着鏈接一個:)你見過這個(尤其是奧利的回答)? http://stackoverflow.com/questions/5529685/post-doesnt-send-data-as-json-but-as-x-www-form-urlencoded-instead – Antenka

回答

2

能否請您檢查代碼,

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

之前實施得當,

router.post('/savegrades', 

基於您的評論,

能否請你嘗試加入嘗試添加MIME類型(內容類型)在客戶端。

+0

它是。我的'app.js'文件包含bodyparser和其他配置。我在'app.js'中的最後一行是'app.use('/',db)'Where db是我的路由器(上面的服務器代碼位於此處)。 – iamtesla

+0

更新了我的回答 –

+0

@Shathik謝謝!它現在正確地工作。客戶端代碼現在是:'$ .post(「/ savegrades',{classIndex:」classIndexId「},'json');' – iamtesla

1

試試這個,通過郵遞員發送數據以驗證數據實際上是正在添加,然後通過功能

var bodyParser = require('body-parser'); 
app.use(bodyParser.json()); // support json encoded bodies 
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies 

app.post('/savegrades', function(req, res) { 
    console.log("Class index: " + req.body.classIndex); 
    console.log(req.body); 
    res.send(200); 
});