Javascript 接受 POST 请求的 Node.js 服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12006417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js server that accepts POST requests
提问by Ostap Hnatyuk
I'm trying to allow javascript to communicate with a Node.js server.
我正在尝试允许 javascript 与 Node.js 服务器进行通信。
POST request (web browser)
POST 请求(网络浏览器)
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.
现在 Node.js 服务器代码看起来像这样。在用于 GET 请求之前。我不知道如何使它与 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.
在此先感谢您的帮助。
回答by Hector Correa
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'...) 来捕获正文的内容。
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}`)
If you use something like Express.jsand Bodyparserthen it would look like this since Express will handle the request.body concatenation
如果您使用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}`)
回答by Masoud Siahkali
Receive POST and GET request in nodejs :
在 nodejs 中接收 POST 和 GET 请求:
1).Server
1).服务器
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();