我正在尝试允许javascript与Node.js服务器通信。
POST请求(Web浏览器)
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请求一起使用。
服务器(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串联
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}`)