栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

接受POST请求的Node.js服务器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

接受POST请求的Node.js服务器

以下代码显示了如何从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 = 3000const 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 = 3000app.listen(port)console.log(`Listening at http://localhost:${port}`)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/392094.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号