我试图允许javascript与 node 通信.js服务器.

POST request (web browser)

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

现在是 node .js服务器代码如下所示.在用于GET请求之前.我不知道该如何处理POST请求.

Server (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所说,您需要使用请求.关于('数据'…)捕捉身体的内容.

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.jsBodyparser这样的值,那么它看起来是这样的,因为Express将处理请求.体连接

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')
})

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

Node.js相关问答推荐

使用prisma迁移到SQL失败

Twilio-获取呼叫录音不起作用的请求

Stripe webhook无法访问Express请求原始正文

如何在.npmrc中添加 comments ?

MongoDB如果文档S的字段小于另一个字段,则将该字段加一

如何防止 Chrome 通过 Selenium 崩溃?

在 Header 中使用 Authorization 方法和新的附加参数:accessToken 有什么区别?

带有事件网格的 Azure 函数在没有 ngrok 的情况下在本地运行

在 NodeJS/ESP32 中通过 WebSocket 发送二进制数据 - 如何识别二进制和文本消息

Node.js 大文件上传到 MongoDB 阻塞了事件循环和工作池

使用 grunt 服务器,如何将所有请求重定向到根 url?

如何正确使用 package.json 中的关键字属性?

Nodejs-console.error vs util.debug

mongoose 模式中的嵌套对象

Node_redis - 如何删除密钥?

使用 Node.js 和 Express 进行简单的 API 调用

安装Node.js 安装n 安装Node.js?

如何仅在丢失的路由上将 Express.js 设置为 404?

NodeJS 中的 HTTPS 请求

将 Heroku App 连接到 Atlas MongoDB 云服务