以下代码显示了如何从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 = `
Name:`
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 = `
Name:`
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}`)