简体   繁体   English

如何使用Node.js从服务器端的AJAX POST函数接收数据?

[英]How to receive data from an AJAX POST function at the server side with Node.js?

I am trying to send data to the server with the Ajax POST function, and then receive it at the server side with Node.js (and then manipulate it there) but the only problem is that I am unable to find any function at the Node.js side to allow me,accomplish this.I would really like it if you guys could help me out on how to do this as even related threads, I visited on many websites were not very helpful. 我试图使用Ajax POST函数将数据发送到服务器,然后使用Node.js在服务器端接收数据(然后在那儿进行操作),但是唯一的问题是我无法在Node上找到任何函数.js方面允许我完成此操作。我真的很想它,如果你们可以帮助我解决这个问题,因为即使是相关线程,我在许多网站上访问都没有太大帮助。

Thanks 谢谢

It will be much easier for you to use some Node-framework like express, to handle all that routes and requests. 使用诸如Express这样的Node框架来处理所有路由和请求会容易得多。

You can install it and body-parser module with these commands: 您可以使用以下命令安装它和body-parser模块:

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

Visit express API References to find out more: http://expressjs.com/4x/api.html 访问express 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);

Inside your app.post() route you can get access to any post data using req.body. 在app.post()路由内部,您可以使用req.body访问任何发布数据。 So your S_POST["name"] will be req.body.name in this case. 因此,在这种情况下,您的S_POST [“ name”]将为req.body.name。

here's a simple example: 这是一个简单的例子:

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;
    }
}

Also see this page . 另请参阅此页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM