2015-05-03 79 views
2

我想用Ajax POST函數發送數據到服務器,然後在服務器端用Node.js接收它(然後在那裏操縱它),但唯一的問題是我無法在Node.js方面允許我完成這項工作。如果你們能夠幫助我解決如何做到這一點甚至相關的線程,我真的很喜歡它,我在很多網站上訪問過的並不是很有幫助。如何使用Node.js從服務器端的AJAX POST函數接收數據?

感謝

+0

ajax請求將從前端完成。 Node.js可以實現該「服務」(/ POST端點)。我在這裏錯過了什麼嗎? –

+0

我沒有node.js的知識,但OP是否要求類似的東西? $ resOfTeamOne = $ _POST [「teamOne」]; //其中teamOne是前端輸入名稱 – Mnemonics

回答

1

使用像express這樣的Node-framework來處理所有的路由和請求會容易得多。

您可以使用這些命令安裝它和身體的解析器模塊:

npm install express --save 
npm install body-parser --save 

訪問快遞API參考,以瞭解更多:http://expressjs.com/4x/api.html

var express = require('express'); 
var bodyParser = require('body-parser'); 
var app = express(); 

app.use(bodyParser.json()); 

// Handle GET request to '/save' 
app.get('/save', function(req, res, next){ 
    res.send('Some page with the form.'); 
}); 

// Handle POST request to '/save' 
app.post('/save', function(req, res, next) { 
    console.log(req.body); 
    res.json({'status' : 'ok'}); 
}); 

app.listen(3000); 

裏面你app.post()路線,你可以使用req.body訪問任何後期數據。因此,在這種情況下,您的S_POST [「name」]將是req.body.name。

+0

koa可用於此,因爲我聽說它更好。 – TheGhostJoker

+0

@TheGhostJoker是的,當然你可以使用Koa。以下是一個簡單的例子,說明如何使用Koa.js處理GET和POST請求:http://weblogs.asp.net/shijuvarghese/a-simple-crud-demo-with-koa-js – Dyrk

1

這裏有一個簡單的例子:

var http = require('http'); 
http.createServer(function (request, response) { 

    switch(request.url){ 
     case '/formhandler': 
      if(request.method == 'POST'){ 
       request.on('data', function(chunk){ 
        console.log('Received a chunk of data:'); 
        console.log(chunk.tostring()); 
       }); 

       request.on('end', function(){ 
        response.writeHead(200, "OK", {'Content-Type' : 'text/html'}); 
        response.end() 
       }); 
      } 
      break; 
    } 
} 

另見this page

相關問題