节点。接受POST请求的js服务器

时间:2021-10-20 16:15:04

I'm trying to allow javascript to communicate with a Node.js server.

我试图让javascript与节点通信。js服务器。

POST request (Javascript)

POST请求(Javascript)

var http = new XMLHttpRequest();
var params = "text=stuff";
http.open("POST", "http://someurl.net:8080", true);

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

alert(http.onreadystatechange);
http.onreadystatechange = function() {
  if (http.readyState == 4 && http.status == 200) {
    alert(http.responseText);
  }
}

http.send(params);

Right now the Node.js server code looks like this. Before it was used for GET requests. I'm not sure how to make it work with POST requests.

现在的节点。js服务器代码如下所示。在它被用于获取请求之前。我不知道如何让它处理POST请求。

Server (Node.js)

服务器(node . js)

var server = http.createServer(function (request, response) {
  var queryData = url.parse(request.url, true).query;

  if (queryData.text) {
    convert('engfemale1', queryData.text, response);
    response.writeHead(200, {
      'Content-Type': 'audio/mp3', 
      'Content-Disposition': 'attachment; filename="tts.mp3"'
    });
  } 
  else {
    response.end('No text to convert.');
  }
}).listen(8080);

Thanks in advance for your help.

谢谢你的帮助。

2 个解决方案

#1


81  

The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.

下面的代码展示了如何从HTML表单中读取值。正如@pimvdb所说,您需要使用request.on(“data”…)来捕获主体的内容。

http = require('http');
fs = require('fs');
server = http.createServer( function(req, res) {

    console.dir(req.param);

    if (req.method == 'POST') {
        console.log("POST");
        var body = '';
        req.on('data', function (data) {
            body += data;
            console.log("Partial body: " + body);
        });
        req.on('end', function () {
            console.log("Body: " + body);
        });
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end('post received');
    }
    else
    {
        console.log("GET");
        //var html = '<html><body><form method="post" action="http://localhost:3000">Name: <input type="text" name="name" /><input type="submit" value="Submit" /></form></body>';
        var html = fs.readFileSync('index.html');
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(html);
    }

});

port = 3000;
host = '127.0.0.1';
server.listen(port, host);
console.log('Listening at http://' + host + ':' + port);

If you use something like Express.js then it can be simplified to something like this since Express takes care of a lot of the HTTP plumbing for you:

如果你使用一些像Express这样的东西。然后,它可以被简化成这样,因为Express为你提供了很多HTTP管道:

var express = require('express');
var fs = require('fs');
var app = express();

app.use(express.bodyParser());

app.get('/', function(req, res){
    console.log('GET /')
    //var html = '<html><body><form method="post" action="http://localhost:3000">Name: <input type="text" name="name" /><input type="submit" value="Submit" /></form></body>';
    var html = fs.readFileSync('index.html');
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(html);
});

app.post('/', function(req, res){
    console.log('POST /');
    console.dir(req.body);
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('thanks');
});

port = 3000;
app.listen(port);
console.log('Listening at http://localhost:' + port)

In both cases I am reading "index.html" which is a very basic HTML file with the JavaScript that you are using:

在这两种情况下,我都在阅读“索引”。这是一个非常基本的html文件,带有你正在使用的JavaScript:

<html>
<body>
    <form method="post" action="http://localhost:3000">
        Name: <input type="text" name="name" />
        <input type="submit" value="Submit" />
    </form>

    <script type="text/JavaScript">
        console.log('begin');
        var http = new XMLHttpRequest();
        var params = "text=stuff";
        http.open("POST", "http://localhost:3000", true);

        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        //http.setRequestHeader("Content-length", params.length);
        //http.setRequestHeader("Connection", "close");

        http.onreadystatechange = function() {
            console.log('onreadystatechange');
            if (http.readyState == 4 && http.status == 200) {
                alert(http.responseText);
            }
            else {
                console.log('readyState=' + http.readyState + ', status: ' + http.status);
            }
        }

        console.log('sending...')
        http.send(params);
        console.log('end');

    </script>

</body>
</html>

#2


4  

Receive POST and GET request in nodejs :

在nodejs中接收邮件和请求:

1).Server

1).Server

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

    response.writeHead(200,{"Content-Type":"text\plain"});
    if(request.method == "GET")
        {
            response.end("received GET request.")
        }
    else if(request.method == "POST")
        {
            response.end("received POST request.");
        }
    else
        {
            response.end("Undefined request .");
        }
});

server.listen(8000);
console.log("Server running on port 8000");

2). Client :

2)。客户:

var http = require('http');

var option = {
    hostname : "localhost" ,
    port : 8000 ,
    method : "POST",
    path : "/"
} 

    var request = http.request(option , function(resp){
       resp.on("data",function(chunck){
           console.log(chunck.toString());
       }) 
    })
    request.end();

#1


81  

The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.

下面的代码展示了如何从HTML表单中读取值。正如@pimvdb所说,您需要使用request.on(“data”…)来捕获主体的内容。

http = require('http');
fs = require('fs');
server = http.createServer( function(req, res) {

    console.dir(req.param);

    if (req.method == 'POST') {
        console.log("POST");
        var body = '';
        req.on('data', function (data) {
            body += data;
            console.log("Partial body: " + body);
        });
        req.on('end', function () {
            console.log("Body: " + body);
        });
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end('post received');
    }
    else
    {
        console.log("GET");
        //var html = '<html><body><form method="post" action="http://localhost:3000">Name: <input type="text" name="name" /><input type="submit" value="Submit" /></form></body>';
        var html = fs.readFileSync('index.html');
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(html);
    }

});

port = 3000;
host = '127.0.0.1';
server.listen(port, host);
console.log('Listening at http://' + host + ':' + port);

If you use something like Express.js then it can be simplified to something like this since Express takes care of a lot of the HTTP plumbing for you:

如果你使用一些像Express这样的东西。然后,它可以被简化成这样,因为Express为你提供了很多HTTP管道:

var express = require('express');
var fs = require('fs');
var app = express();

app.use(express.bodyParser());

app.get('/', function(req, res){
    console.log('GET /')
    //var html = '<html><body><form method="post" action="http://localhost:3000">Name: <input type="text" name="name" /><input type="submit" value="Submit" /></form></body>';
    var html = fs.readFileSync('index.html');
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(html);
});

app.post('/', function(req, res){
    console.log('POST /');
    console.dir(req.body);
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('thanks');
});

port = 3000;
app.listen(port);
console.log('Listening at http://localhost:' + port)

In both cases I am reading "index.html" which is a very basic HTML file with the JavaScript that you are using:

在这两种情况下,我都在阅读“索引”。这是一个非常基本的html文件,带有你正在使用的JavaScript:

<html>
<body>
    <form method="post" action="http://localhost:3000">
        Name: <input type="text" name="name" />
        <input type="submit" value="Submit" />
    </form>

    <script type="text/JavaScript">
        console.log('begin');
        var http = new XMLHttpRequest();
        var params = "text=stuff";
        http.open("POST", "http://localhost:3000", true);

        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        //http.setRequestHeader("Content-length", params.length);
        //http.setRequestHeader("Connection", "close");

        http.onreadystatechange = function() {
            console.log('onreadystatechange');
            if (http.readyState == 4 && http.status == 200) {
                alert(http.responseText);
            }
            else {
                console.log('readyState=' + http.readyState + ', status: ' + http.status);
            }
        }

        console.log('sending...')
        http.send(params);
        console.log('end');

    </script>

</body>
</html>

#2


4  

Receive POST and GET request in nodejs :

在nodejs中接收邮件和请求:

1).Server

1).Server

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

    response.writeHead(200,{"Content-Type":"text\plain"});
    if(request.method == "GET")
        {
            response.end("received GET request.")
        }
    else if(request.method == "POST")
        {
            response.end("received POST request.");
        }
    else
        {
            response.end("Undefined request .");
        }
});

server.listen(8000);
console.log("Server running on port 8000");

2). Client :

2)。客户:

var http = require('http');

var option = {
    hostname : "localhost" ,
    port : 8000 ,
    method : "POST",
    path : "/"
} 

    var request = http.request(option , function(resp){
       resp.on("data",function(chunck){
           console.log(chunck.toString());
       }) 
    })
    request.end();