html post no js,接受POST请求的Node.js服务器

这篇博客展示了如何在Node.js中创建一个HTTP服务器,用于处理来自HTML表单的POST请求。通过监听'data'和'end'事件,可以获取并打印请求正文内容。此外,还给出了使用Express.js和body-parser中间件处理POST请求的示例,简化了获取request.body的过程。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值