2017-04-12 23 views
0

後的數據這是我的jQuery代碼:如何從jQuery的接收的NodeJS

$.ajax({ 
      url: 'http://localhost:3000/generatePDF', 
      data: '{"data": "TEST"}', /* It is about the content "TEST" that I would like to receive/get */ 
      type: 'POST', 
      success: function (data) { 
       console.log('Success: '); 
      }, 
      error: function (xhr, status, error) { 
       console.log('Error: ' + error.message); 
      } 
     }); 

這是我的代碼在我的NodeJS服務器:

app.post("/generatePDF", function (req, res) { 
    console.log(req); 
    res.sendStatus(200); 
    return; 
}); 

我想收到我的帖子我使用jQuery代碼發送的數據。我怎樣才能做到這一點?或者我可以用簡單的Javascript來做到這一點?

+0

你使用快遞嗎? –

回答

1

最簡單的方法是使用Express服務器和身體的解析器,https://github.com/expressjs/body-parser

這樣你的NodeJS服務器可以沿着線路看;

var express = require("express"); 
var bodyParser = require("body-parser"); 

var app = express(); 
var PORT = process.env.PORT || 3001; 

app.use(bodyParser.json()); 

app.post("/generatePDF", function (req, res) { 
    console.log(req.body); 
    res.json({ 
     status: 'OK' 
    }) 
}); 

app.listen(PORT,() => { 
    console.log("Server running at http://localhost:" + PORT); 
}); 

捲曲是結果;

$ curl -X POST "http://localhost:3001/generatePDF" -H "Content-Type: application/json" --data '{"data": "TEST"}' 
{"status":"OK"} 

NodeJS Server Logs;

$ node server.js 
Server running at http://localhost:3001 
{ data: 'TEST' } 

請確保您發送內容類型:應用程序/ JSON頭與POST的API。

您可以通過在$ .ajax選項對象中添加新鍵來將標題添加到調用中;

$.ajax({ 
    headers: { 'Content-Type': 'application/json' } 
}); 
0

感謝Christian,我找到了解決方案。

我需要執行下面的代碼:

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

但是,爲什麼?

+1

這是由於jquery發送帶有值爲「application/x-www-form-urlencoded; charset = UTF-8」的Content-Type標頭的發佈請求作爲默認值。 bodyParser使單獨的.json()和.urlencoded()方法成爲獨立的,之前它們曾經是在同一個bodyParser()函數後面。 如果您想在nodejs服務器中將數據作爲json處理,我強烈建議您在應用程序中使用bodyParser.json(),並按照我的答案中的說明在POST請求中發送Content-Type:application/json標頭。 – Rikusor

+0

@庫克謝謝你解釋得很好 – Johnnybossboy

相關問題