最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

接受POST请求的Node.js服务器

IT培训 admin 11浏览 0评论

接受POST请求的Node.js服务器

我正在尝试允许javascript与Node.js服务器通信。

POST请求(Web浏览器)

var http = new XMLHttpRequest();
var params = "text=stuff";
http.open("POST", ":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);

现在,Node.js服务器代码如下所示。在用于GET请求之前。我不确定如何使它与POST请求一起工作。

服务器(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);

在此先感谢您的帮助。

回答如下:

以下代码显示如何从HTML表单中读取值。正如@pimvdb所说,你需要使用request.on('data'...)来捕获正文的内容。

const http = require('http')

const server = http.createServer(function(request, response) {
  console.dir(request.param)

  if (request.method == 'POST') {
    console.log('POST')
    var body = ''
    request.on('data', function(data) {
      body += data
      console.log('Partial body: ' + body)
    })
    request.on('end', function() {
      console.log('Body: ' + body)
      response.writeHead(200, {'Content-Type': 'text/html'})
      response.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>
            </html>`
    response.writeHead(200, {'Content-Type': 'text/html'})
    response.end(html)
  }
})

const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)


如果你使用像Express.js和Bodyparser这样的东西,它会看起来像这样,因为Express会处理request.body concatenation

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

app.use(express.bodyParser())

app.get('/', function(request, response) {
  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>
    </html>`
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end(html)
})

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

port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)

接受POST请求的Node.js服务器

我正在尝试允许javascript与Node.js服务器通信。

POST请求(Web浏览器)

var http = new XMLHttpRequest();
var params = "text=stuff";
http.open("POST", ":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);

现在,Node.js服务器代码如下所示。在用于GET请求之前。我不确定如何使它与POST请求一起工作。

服务器(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);

在此先感谢您的帮助。

回答如下:

以下代码显示如何从HTML表单中读取值。正如@pimvdb所说,你需要使用request.on('data'...)来捕获正文的内容。

const http = require('http')

const server = http.createServer(function(request, response) {
  console.dir(request.param)

  if (request.method == 'POST') {
    console.log('POST')
    var body = ''
    request.on('data', function(data) {
      body += data
      console.log('Partial body: ' + body)
    })
    request.on('end', function() {
      console.log('Body: ' + body)
      response.writeHead(200, {'Content-Type': 'text/html'})
      response.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>
            </html>`
    response.writeHead(200, {'Content-Type': 'text/html'})
    response.end(html)
  }
})

const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)


如果你使用像Express.js和Bodyparser这样的东西,它会看起来像这样,因为Express会处理request.body concatenation

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

app.use(express.bodyParser())

app.get('/', function(request, response) {
  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>
    </html>`
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end(html)
})

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

port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论